<!DOCTYPE html>
<html >

<head>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Python3学习教程</title>
  <meta name="description" content="Python3学习教程">
  <meta name="generator" content="bookdown 0.5 and GitBook 2.6.7">

  <meta property="og:title" content="Python3学习教程" />
  <meta property="og:type" content="book" />
  
  
  
  

  <meta name="twitter:card" content="summary" />
  <meta name="twitter:title" content="Python3学习教程" />
  
  
  

<meta name="author" content="易生信培训团队">
<meta name="author" content="联系我们: train@ehbio.com">
<meta name="author" content="抱歉，转成PDF后部分格式问题还未解决，会继续更新调整">


<meta name="date" content="2018-05-09">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  
  
<link rel="prev" href="pythonbasic.html">
<link rel="next" href="Python-plot-WXN.html">
<script src="libs/jquery-2.2.3/jquery.min.js"></script>
<link href="libs/gitbook-2.6.7/css/style.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-bookdown.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-highlight.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-search.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-fontsettings.css" rel="stylesheet" />









<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
  margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
code > span.dt { color: #902000; } /* DataType */
code > span.dv { color: #40a070; } /* DecVal */
code > span.bn { color: #40a070; } /* BaseN */
code > span.fl { color: #40a070; } /* Float */
code > span.ch { color: #4070a0; } /* Char */
code > span.st { color: #4070a0; } /* String */
code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
code > span.ot { color: #007020; } /* Other */
code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
code > span.fu { color: #06287e; } /* Function */
code > span.er { color: #ff0000; font-weight: bold; } /* Error */
code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #880000; } /* Constant */
code > span.sc { color: #4070a0; } /* SpecialChar */
code > span.vs { color: #4070a0; } /* VerbatimString */
code > span.ss { color: #bb6688; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #19177c; } /* Variable */
code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code > span.op { color: #666666; } /* Operator */
code > span.bu { } /* BuiltIn */
code > span.ex { } /* Extension */
code > span.pp { color: #bc7a00; } /* Preprocessor */
code > span.at { color: #7d9029; } /* Attribute */
code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
</style>

<link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>



  <div class="book without-animation with-summary font-size-2 font-family-1" data-basepath=".">

    <div class="book-summary">
      <nav role="navigation">

<ul class="summary">
<li><a href="http://www.ehbio.com"><img src="http://www.ehbio.com/logos/ehbio_gitbook_logo.png" width="95%"></a></li>

<li class="divider"></li>
<li class="chapter" data-level="" data-path="index.html"><a href="index.html"><i class="fa fa-check"></i>EHBIO Gene Technology</a></li>
<li class="chapter" data-level="1" data-path="pythonbasic.html"><a href="pythonbasic.html"><i class="fa fa-check"></i><b>1</b> Python基础</a><ul>
<li class="chapter" data-level="1.1" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.1"><i class="fa fa-check"></i><b>1.1</b> 交互模式下表达式</a></li>
<li class="chapter" data-level="1.2" data-path="pythonbasic.html"><a href="pythonbasic.html#pythonintfloatstr"><i class="fa fa-check"></i><b>1.2</b> Python中的数据类型：整数（int）、浮点（float）和字符串（str）</a></li>
<li class="chapter" data-level="1.3" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.3"><i class="fa fa-check"></i><b>1.3</b> 字符串的连接和复制</a></li>
<li class="chapter" data-level="1.4" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.4"><i class="fa fa-check"></i><b>1.4</b> 变量</a></li>
<li class="chapter" data-level="1.5" data-path="pythonbasic.html"><a href="pythonbasic.html#helloworld.py"><i class="fa fa-check"></i><b>1.5</b> 第一小程序HelloWorld.py</a></li>
<li class="chapter" data-level="1.6" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.6"><i class="fa fa-check"></i><b>1.6</b> 逻辑和比较操作</a><ul>
<li class="chapter" data-level="1.6.1" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.6.1"><i class="fa fa-check"></i><b>1.6.1</b> 布尔逻辑值</a></li>
<li class="chapter" data-level="1.6.2" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.6.2"><i class="fa fa-check"></i><b>1.6.2</b> 比较操作符</a></li>
<li class="chapter" data-level="1.6.3" data-path="pythonbasic.html"><a href="pythonbasic.html#-and-or-not"><i class="fa fa-check"></i><b>1.6.3</b> 布尔操作符 and or not</a></li>
<li class="chapter" data-level="1.6.4" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.6.4"><i class="fa fa-check"></i><b>1.6.4</b> 布尔操作和比较操作符</a></li>
</ul></li>
<li class="chapter" data-level="1.7" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.7"><i class="fa fa-check"></i><b>1.7</b> 控制流</a><ul>
<li class="chapter" data-level="1.7.1" data-path="pythonbasic.html"><a href="pythonbasic.html#if-"><i class="fa fa-check"></i><b>1.7.1</b> if 语句</a></li>
<li class="chapter" data-level="1.7.2" data-path="pythonbasic.html"><a href="pythonbasic.html#elif-"><i class="fa fa-check"></i><b>1.7.2</b> elif 否则如果</a></li>
<li class="chapter" data-level="1.7.3" data-path="pythonbasic.html"><a href="pythonbasic.html#while"><i class="fa fa-check"></i><b>1.7.3</b> while循环</a></li>
<li class="chapter" data-level="1.7.4" data-path="pythonbasic.html"><a href="pythonbasic.html#breakcontinue"><i class="fa fa-check"></i><b>1.7.4</b> break和continue</a></li>
<li class="chapter" data-level="1.7.5" data-path="pythonbasic.html"><a href="pythonbasic.html#for--range"><i class="fa fa-check"></i><b>1.7.5</b> for 和 range（）函数</a></li>
<li class="chapter" data-level="1.7.6" data-path="pythonbasic.html"><a href="pythonbasic.html#range"><i class="fa fa-check"></i><b>1.7.6</b> range()函数（开始，停止，步长）</a></li>
</ul></li>
<li class="chapter" data-level="1.8" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.8"><i class="fa fa-check"></i><b>1.8</b> 导入模块</a></li>
<li class="chapter" data-level="1.9" data-path="pythonbasic.html"><a href="pythonbasic.html#-"><i class="fa fa-check"></i><b>1.9</b> 函数： 内置函数、自定义函数</a><ul>
<li class="chapter" data-level="1.9.1" data-path="pythonbasic.html"><a href="pythonbasic.html#printlen-input-intstr"><i class="fa fa-check"></i><b>1.9.1</b> 函数print（），len （）,input （），int（），str（）均为内置函数</a></li>
</ul></li>
<li class="chapter" data-level="1.10" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.10"><i class="fa fa-check"></i><b>1.10</b> 局部和全局作用域</a></li>
<li class="chapter" data-level="1.11" data-path="pythonbasic.html"><a href="pythonbasic.html#global"><i class="fa fa-check"></i><b>1.11</b> 声明为全局变量global</a></li>
<li class="chapter" data-level="1.12" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.12"><i class="fa fa-check"></i><b>1.12</b> 异常的处理</a></li>
<li class="chapter" data-level="1.13" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.13"><i class="fa fa-check"></i><b>1.13</b> 列表</a></li>
<li class="chapter" data-level="1.14" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.14"><i class="fa fa-check"></i><b>1.14</b> 字符串和元组</a></li>
<li class="chapter" data-level="1.15" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.15"><i class="fa fa-check"></i><b>1.15</b> 引用</a></li>
<li class="chapter" data-level="1.16" data-path="pythonbasic.html"><a href="pythonbasic.html#--"><i class="fa fa-check"></i><b>1.16</b> 字典 键：值 对</a></li>
<li class="chapter" data-level="1.17" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.17"><i class="fa fa-check"></i><b>1.17</b> 字典与列表</a><ul>
<li class="chapter" data-level="1.17.1" data-path="pythonbasic.html"><a href="pythonbasic.html#keysvaluesitems"><i class="fa fa-check"></i><b>1.17.1</b> keys()、values（）和items( )</a></li>
</ul></li>
<li class="chapter" data-level="1.18" data-path="pythonbasic.html"><a href="pythonbasic.html#section-1.18"><i class="fa fa-check"></i><b>1.18</b> 字符串操作</a></li>
</ul></li>
<li class="chapter" data-level="2" data-path="py3-ct.html"><a href="py3-ct.html"><i class="fa fa-check"></i><b>2</b> Python 教程</a><ul>
<li class="chapter" data-level="2.1" data-path="py3-ct.html"><a href="py3-ct.html#section-2.1"><i class="fa fa-check"></i><b>2.1</b> 背景介绍</a><ul>
<li class="chapter" data-level="2.1.1" data-path="py3-ct.html"><a href="py3-ct.html#section-2.1.1"><i class="fa fa-check"></i><b>2.1.1</b> 编程开篇</a></li>
<li class="chapter" data-level="2.1.2" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.1.2</b> 为什么学习Python</a></li>
<li class="chapter" data-level="2.1.3" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.1.3</b> Python常用包</a></li>
<li class="chapter" data-level="2.1.4" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.1.4</b> 怎么学习Python</a></li>
<li class="chapter" data-level="2.1.5" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.1.5</b> Python学习的几个阶段</a></li>
<li class="chapter" data-level="2.1.6" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.1.6</b> 如何安装Python</a></li>
<li class="chapter" data-level="2.1.7" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.1.7</b> 如何运行Python命令和脚本</a></li>
<li class="chapter" data-level="2.1.8" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.1.8</b> 使用什么编辑器写Python脚本</a></li>
</ul></li>
<li class="chapter" data-level="2.2" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.2</b> Python程序事例</a></li>
<li class="chapter" data-level="2.3" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.3</b> Python语法</a><ul>
<li class="chapter" data-level="2.3.1" data-path="py3-ct.html"><a href="py3-ct.html#section-2.3.1"><i class="fa fa-check"></i><b>2.3.1</b> 层级缩进</a></li>
<li class="chapter" data-level="2.3.2" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.3.2</b> Python作为计算器的使用</a></li>
<li class="chapter" data-level="2.3.3" data-path="py3-ct.html"><a href="py3-ct.html#section-2.3.3"><i class="fa fa-check"></i><b>2.3.3</b> 变量、数据结构、流程控制</a></li>
</ul></li>
<li class="chapter" data-level="2.4" data-path="py3-ct.html"><a href="py3-ct.html#section-2.4"><i class="fa fa-check"></i><b>2.4</b> 输入输出</a><ul>
<li class="chapter" data-level="2.4.1" data-path="py3-ct.html"><a href="py3-ct.html#section-2.4.1"><i class="fa fa-check"></i><b>2.4.1</b> 交互式输入输出</a></li>
<li class="chapter" data-level="2.4.2" data-path="py3-ct.html"><a href="py3-ct.html#section-2.4.2"><i class="fa fa-check"></i><b>2.4.2</b> 文件读写</a></li>
</ul></li>
<li class="chapter" data-level="2.5" data-path="py3-ct.html"><a href="py3-ct.html#section-2.5"><i class="fa fa-check"></i><b>2.5</b> 实战练习（一）</a><ul>
<li class="chapter" data-level="2.5.1" data-path="py3-ct.html"><a href="py3-ct.html#section-2.5.1"><i class="fa fa-check"></i><b>2.5.1</b> 背景知识</a></li>
<li class="chapter" data-level="2.5.2" data-path="pythonbasic.html"><a href="pythonbasic.html#-"><i class="fa fa-check"></i><b>2.5.2</b> 作业 (一)</a></li>
</ul></li>
<li class="chapter" data-level="2.6" data-path="py3-ct.html"><a href="py3-ct.html#section-2.6"><i class="fa fa-check"></i><b>2.6</b> 函数操作</a><ul>
<li class="chapter" data-level="2.6.1" data-path="py3-ct.html"><a href="py3-ct.html#section-2.6.1"><i class="fa fa-check"></i><b>2.6.1</b> 作业（二）</a></li>
</ul></li>
<li class="chapter" data-level="2.7" data-path="py3-ct.html"><a href="py3-ct.html#section-2.7"><i class="fa fa-check"></i><b>2.7</b> 模块</a></li>
<li class="chapter" data-level="2.8" data-path="py3-ct.html"><a href="py3-ct.html#section-2.8"><i class="fa fa-check"></i><b>2.8</b> 命令行参数</a><ul>
<li class="chapter" data-level="2.8.1" data-path="py3-ct.html"><a href="py3-ct.html#section-2.8.1"><i class="fa fa-check"></i><b>2.8.1</b> 作业（三）</a></li>
</ul></li>
<li class="chapter" data-level="2.9" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.9</b> 更多Python内容</a><ul>
<li class="chapter" data-level="2.9.1" data-path="py3-ct.html"><a href="py3-ct.html#section-2.9.1"><i class="fa fa-check"></i><b>2.9.1</b> <strong>单语句块</strong></a></li>
<li class="chapter" data-level="2.9.2" data-path="py3-ct.html"><a href="py3-ct.html#section-2.9.2"><i class="fa fa-check"></i><b>2.9.2</b> 列表解析</a></li>
<li class="chapter" data-level="2.9.3" data-path="py3-ct.html"><a href="py3-ct.html#section-2.9.3"><i class="fa fa-check"></i><b>2.9.3</b> 字典解析</a></li>
<li class="chapter" data-level="2.9.4" data-path="py3-ct.html"><a href="py3-ct.html#section-2.9.4"><i class="fa fa-check"></i><b>2.9.4</b> 断言</a></li>
<li class="chapter" data-level="2.9.5" data-path="py3-ct.html"><a href="py3-ct.html#section-2.9.5"><i class="fa fa-check"></i><b>2.9.5</b> 更多字符串方法</a></li>
<li class="chapter" data-level="2.9.6" data-path="py3-ct.html"><a href="py3-ct.html#lambda-map-filer-reduce-"><i class="fa fa-check"></i><b>2.9.6</b> lambda, map, filer, reduce (保留节目)</a></li>
<li class="chapter" data-level="2.9.7" data-path="py3-ct.html"><a href="py3-ct.html#exec-eval-python-"><i class="fa fa-check"></i><b>2.9.7</b> <strong>exec, eval (执行字符串python语句, 保留节目)</strong></a></li>
<li class="chapter" data-level="2.9.8" data-path="py3-ct.html"><a href="py3-ct.html#section-2.9.8"><i class="fa fa-check"></i><b>2.9.8</b> 正则表达式</a></li>
</ul></li>
<li class="chapter" data-level="2.10" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>2.10</b> Python画图</a></li>
<li class="chapter" data-level="2.11" data-path="py3-ct.html"><a href="py3-ct.html#reference"><i class="fa fa-check"></i><b>2.11</b> Reference</a></li>
</ul></li>
<li class="chapter" data-level="3" data-path="Python-plot-WXN.html"><a href="Python-plot-WXN.html"><i class="fa fa-check"></i><b>3</b> Python作图</a><ul>
<li class="chapter" data-level="3.1" data-path="Python-plot-WXN.html"><a href="Python-plot-WXN.html#section-3.1"><i class="fa fa-check"></i><b>3.1</b> 绘图基础</a><ul>
<li class="chapter" data-level="3.1.1" data-path="Python-plot-WXN.html"><a href="Python-plot-WXN.html#figuresubplot-1"><i class="fa fa-check"></i><b>3.1.1</b> Figure和Subplot</a></li>
<li class="chapter" data-level="3.1.2" data-path="Python-plot-WXN.html"><a href="Python-plot-WXN.html#subplot-1"><i class="fa fa-check"></i><b>3.1.2</b> 调整subplot周围间距</a></li>
<li class="chapter" data-level="3.1.3" data-path="Python-plot-WXN.html"><a href="Python-plot-WXN.html#--1"><i class="fa fa-check"></i><b>3.1.3</b> 颜色 标记和线型</a></li>
<li class="chapter" data-level="3.1.4" data-path="py3-ct.html"><a href="py3-ct.html#-1"><i class="fa fa-check"></i><b>3.1.4</b> 刻度、标签和图例</a></li>
<li class="chapter" data-level="3.1.5" data-path="Python-plot-WXN.html"><a href="Python-plot-WXN.html#legend-1"><i class="fa fa-check"></i><b>3.1.5</b> 添加图例legend</a></li>
<li class="chapter" data-level="3.1.6" data-path="py3-ct.html"><a href="py3-ct.html#-1"><i class="fa fa-check"></i><b>3.1.6</b> 注解</a></li>
<li class="chapter" data-level="3.1.7" data-path="py3-ct.html"><a href="py3-ct.html#-1"><i class="fa fa-check"></i><b>3.1.7</b> 图片保存</a></li>
</ul></li>
<li class="chapter" data-level="3.2" data-path="Python-plot-WXN.html"><a href="Python-plot-WXN.html#section-3.2"><i class="fa fa-check"></i><b>3.2</b> 绘图实例</a><ul>
<li class="chapter" data-level="3.2.1" data-path="py3-ct.html"><a href="py3-ct.html#-1"><i class="fa fa-check"></i><b>3.2.1</b> 绘制散点图</a></li>
<li class="chapter" data-level="3.2.2" data-path="py3-ct.html"><a href="py3-ct.html#-1"><i class="fa fa-check"></i><b>3.2.2</b> 折线图</a></li>
<li class="chapter" data-level="3.2.3" data-path="py3-ct.html"><a href="py3-ct.html#-1"><i class="fa fa-check"></i><b>3.2.3</b> 直方图</a></li>
<li class="chapter" data-level="3.2.4" data-path="py3-ct.html"><a href="py3-ct.html#-1"><i class="fa fa-check"></i><b>3.2.4</b> 直条图</a></li>
<li class="chapter" data-level="3.2.5" data-path="py3-ct.html"><a href="py3-ct.html#-1"><i class="fa fa-check"></i><b>3.2.5</b> 箱线图</a></li>
<li class="chapter" data-level="3.2.6" data-path="py3-ct.html"><a href="py3-ct.html#-1"><i class="fa fa-check"></i><b>3.2.6</b> 饼图</a></li>
<li class="chapter" data-level="3.2.7" data-path="Python-plot-WXN.html"><a href="Python-plot-WXN.html#section-3.2.7"><i class="fa fa-check"></i><b>3.2.7</b> 绘制基因矩阵的热图</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="4" data-path="Py3-pratcise-ct.html"><a href="Py3-pratcise-ct.html"><i class="fa fa-check"></i><b>4</b> Python实战</a><ul>
<li class="chapter" data-level="4.1" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>4.1</b> Python实战</a><ul>
<li class="chapter" data-level="4.1.1" data-path="Py3-pratcise-ct.html"><a href="Py3-pratcise-ct.html#id"><i class="fa fa-check"></i><b>4.1.1</b> ID转换</a></li>
<li class="chapter" data-level="4.1.2" data-path="Py3-pratcise-ct.html"><a href="Py3-pratcise-ct.html#section-4.1.2"><i class="fa fa-check"></i><b>4.1.2</b> 每条染色体基因数目统计</a></li>
<li class="chapter" data-level="4.1.3" data-path="Py3-pratcise-ct.html"><a href="Py3-pratcise-ct.html#section-4.1.3"><i class="fa fa-check"></i><b>4.1.3</b> 所有外显子总长度统计</a></li>
</ul></li>
<li class="chapter" data-level="4.2" data-path="py3-ct.html"><a href="py3-ct.html#python"><i class="fa fa-check"></i><b>4.2</b> Python小技巧</a></li>
</ul></li>
<li class="chapter" data-level="5" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html"><i class="fa fa-check"></i><b>5</b> Pandas 学习教程</a><ul>
<li class="chapter" data-level="5.1" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#what-is-pandas"><i class="fa fa-check"></i><b>5.1</b> What is pandas</a></li>
<li class="chapter" data-level="5.2" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#pandas"><i class="fa fa-check"></i><b>5.2</b> Pandas读取文件</a><ul>
<li class="chapter" data-level="5.2.1" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#section-5.2.1"><i class="fa fa-check"></i><b>5.2.1</b> 获取目标文件</a></li>
<li class="chapter" data-level="5.2.2" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#section-5.2.2"><i class="fa fa-check"></i><b>5.2.2</b> 查看目标文件内容和格式</a></li>
<li class="chapter" data-level="5.2.3" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#section-5.2.3"><i class="fa fa-check"></i><b>5.2.3</b> 读取两列文件</a></li>
<li class="chapter" data-level="5.2.4" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#section-5.2.4"><i class="fa fa-check"></i><b>5.2.4</b> 数据表的索引</a></li>
<li class="chapter" data-level="5.2.5" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#section-5.2.5"><i class="fa fa-check"></i><b>5.2.5</b> 读取多列文件</a></li>
<li class="chapter" data-level="5.2.6" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#section-5.2.6"><i class="fa fa-check"></i><b>5.2.6</b> 选取多列数据</a></li>
<li class="chapter" data-level="5.2.7" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#section-5.2.7"><i class="fa fa-check"></i><b>5.2.7</b> 重命名列名字</a></li>
<li class="chapter" data-level="5.2.8" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#section-5.2.8"><i class="fa fa-check"></i><b>5.2.8</b> 合并矩阵</a></li>
<li class="chapter" data-level="5.2.9" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#section-5.2.9"><i class="fa fa-check"></i><b>5.2.9</b> 矩阵数据提取</a></li>
<li class="chapter" data-level="5.2.10" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#meta-data"><i class="fa fa-check"></i><b>5.2.10</b> 读取META data文件</a></li>
</ul></li>
<li class="chapter" data-level="5.3" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#pandas"><i class="fa fa-check"></i><b>5.3</b> Pandas写入文件</a><ul>
<li class="chapter" data-level="5.3.1" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#section-5.3.1"><i class="fa fa-check"></i><b>5.3.1</b> 写入文本文件</a></li>
</ul></li>
<li class="chapter" data-level="5.4" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#pandas"><i class="fa fa-check"></i><b>5.4</b> PANDAS矩阵的小应用</a></li>
<li class="chapter" data-level="5.5" data-path="py3-pandas-ct.html"><a href="py3-pandas-ct.html#seaborn"><i class="fa fa-check"></i><b>5.5</b> Seaborn绘图</a></li>
</ul></li>
<li class="chapter" data-level="6" data-path="numpy-scipy.html"><a href="numpy-scipy.html"><i class="fa fa-check"></i><b>6</b> Python科学计算</a><ul>
<li class="chapter" data-level="6.1" data-path="numpy-scipy.html"><a href="numpy-scipy.html#numpy"><i class="fa fa-check"></i><b>6.1</b> NumPy</a><ul>
<li class="chapter" data-level="6.1.1" data-path="numpy-scipy.html"><a href="numpy-scipy.html#numpy"><i class="fa fa-check"></i><b>6.1.1</b> NumPy数组</a></li>
<li class="chapter" data-level="6.1.2" data-path="numpy-scipy.html"><a href="numpy-scipy.html#numpy"><i class="fa fa-check"></i><b>6.1.2</b> 布尔语句和NumPy数组</a></li>
<li class="chapter" data-level="6.1.3" data-path="numpy-scipy.html"><a href="numpy-scipy.html#numpy"><i class="fa fa-check"></i><b>6.1.3</b> NumPy读写文件</a></li>
<li class="chapter" data-level="6.1.4" data-path="numpy-scipy.html"><a href="numpy-scipy.html#numpymath"><i class="fa fa-check"></i><b>6.1.4</b> NumPy的Math模块</a></li>
</ul></li>
<li class="chapter" data-level="6.2" data-path="numpy-scipy.html"><a href="numpy-scipy.html#scipy"><i class="fa fa-check"></i><b>6.2</b> SciPy</a><ul>
<li class="chapter" data-level="6.2.1" data-path="numpy-scipy.html"><a href="numpy-scipy.html#section-6.2.1"><i class="fa fa-check"></i><b>6.2.1</b> 最优化和最小化</a></li>
<li class="chapter" data-level="6.2.2" data-path="numpy-scipy.html"><a href="numpy-scipy.html#section-6.2.2"><i class="fa fa-check"></i><b>6.2.2</b> 插值</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="7" data-path="Py3-test.html"><a href="Py3-test.html"><i class="fa fa-check"></i><b>7</b> 易生信Python培训练习和考核题目</a></li>
<li class="chapter" data-level="8" data-path="references.html"><a href="references.html"><i class="fa fa-check"></i><b>8</b> 生信教程文章集锦</a><ul>
<li class="chapter" data-level="8.1" data-path="references.html"><a href="references.html#section-8.1"><i class="fa fa-check"></i><b>8.1</b> 生信宝典</a><ul>
<li class="chapter" data-level="8.1.1" data-path="references.html"><a href="references.html#section-8.1.1"><i class="fa fa-check"></i><b>8.1.1</b> 系列教程</a></li>
<li class="chapter" data-level="8.1.2" data-path="references.html"><a href="references.html#ngs"><i class="fa fa-check"></i><b>8.1.2</b> NGS分析工具评估</a></li>
<li class="chapter" data-level="8.1.3" data-path="references.html"><a href="references.html#section-8.1.3"><i class="fa fa-check"></i><b>8.1.3</b> 宏基因组教程</a></li>
<li class="chapter" data-level="8.1.4" data-path="references.html"><a href="references.html#section-8.1.4"><i class="fa fa-check"></i><b>8.1.4</b> 系列宣传</a></li>
<li class="chapter" data-level="8.1.5" data-path="references.html"><a href="references.html#section-8.1.5"><i class="fa fa-check"></i><b>8.1.5</b> 生信生物知识</a></li>
<li class="chapter" data-level="8.1.6" data-path="references.html"><a href="references.html#section-8.1.6"><i class="fa fa-check"></i><b>8.1.6</b> 文献精读</a></li>
<li class="chapter" data-level="8.1.7" data-path="references.html"><a href="references.html#linux"><i class="fa fa-check"></i><b>8.1.7</b> Linux</a></li>
<li class="chapter" data-level="8.1.8" data-path="references.html"><a href="references.html#circos"><i class="fa fa-check"></i><b>8.1.8</b> CIRCOS系列</a></li>
<li class="chapter" data-level="8.1.9" data-path="references.html"><a href="references.html#r"><i class="fa fa-check"></i><b>8.1.9</b> R统计和作图</a></li>
<li class="chapter" data-level="8.1.10" data-path="references.html"><a href="references.html#section-8.1.10"><i class="fa fa-check"></i><b>8.1.10</b> 扩增子三步曲</a></li>
<li class="chapter" data-level="8.1.11" data-path="references.html"><a href="references.html#section-8.1.11"><i class="fa fa-check"></i><b>8.1.11</b> 宏基因组分析专题</a></li>
<li class="chapter" data-level="8.1.12" data-path="references.html"><a href="references.html#ngs"><i class="fa fa-check"></i><b>8.1.12</b> NGS基础</a></li>
<li class="chapter" data-level="8.1.13" data-path="references.html"><a href="references.html#section-8.1.13"><i class="fa fa-check"></i><b>8.1.13</b> 癌症数据库</a></li>
<li class="chapter" data-level="8.1.14" data-path="references.html"><a href="references.html#python-1"><i class="fa fa-check"></i><b>8.1.14</b> Python</a></li>
<li class="chapter" data-level="8.1.15" data-path="references.html"><a href="references.html#ngs"><i class="fa fa-check"></i><b>8.1.15</b> NGS软件</a></li>
<li class="chapter" data-level="8.1.16" data-path="references.html"><a href="references.html#cytoscape"><i class="fa fa-check"></i><b>8.1.16</b> Cytoscape网络图</a></li>
<li class="chapter" data-level="8.1.17" data-path="references.html"><a href="references.html#section-8.1.17"><i class="fa fa-check"></i><b>8.1.17</b> 分子对接</a></li>
<li class="chapter" data-level="8.1.18" data-path="references.html"><a href="references.html#section-8.1.18"><i class="fa fa-check"></i><b>8.1.18</b> 生信宝典之傻瓜式</a></li>
<li class="chapter" data-level="8.1.19" data-path="references.html"><a href="references.html#section-8.1.19"><i class="fa fa-check"></i><b>8.1.19</b> 生信人写程序</a></li>
<li class="chapter" data-level="8.1.20" data-path="references.html"><a href="references.html#section-8.1.20"><i class="fa fa-check"></i><b>8.1.20</b> 小技巧系列</a></li>
<li class="chapter" data-level="8.1.21" data-path="references.html"><a href="references.html#section-8.1.21"><i class="fa fa-check"></i><b>8.1.21</b> 招聘</a></li>
</ul></li>
<li class="chapter" data-level="8.2" data-path="references.html"><a href="references.html#section-8.2"><i class="fa fa-check"></i><b>8.2</b> 宏基因组</a><ul>
<li class="chapter" data-level="8.2.1" data-path="references.html"><a href="references.html#section-8.2.1"><i class="fa fa-check"></i><b>8.2.1</b> 精选文章推荐</a></li>
<li class="chapter" data-level="8.2.2" data-path="references.html"><a href="references.html#section-8.2.2"><i class="fa fa-check"></i><b>8.2.2</b> 培训、会议、征稿、招聘</a></li>
<li class="chapter" data-level="8.2.3" data-path="references.html"><a href="references.html#section-8.2.3"><i class="fa fa-check"></i><b>8.2.3</b> 科研经验</a></li>
<li class="chapter" data-level="8.2.4" data-path="references.html"><a href="references.html#section-8.2.4"><i class="fa fa-check"></i><b>8.2.4</b> 软件和数据库使用</a></li>
<li class="chapter" data-level="8.2.5" data-path="references.html"><a href="references.html#section-8.2.5"><i class="fa fa-check"></i><b>8.2.5</b> 扩增子学习三步曲</a></li>
<li class="chapter" data-level="8.2.6" data-path="py3-ct.html"><a href="py3-ct.html#-1"><i class="fa fa-check"></i><b>8.2.6</b> 宏基因组分析专题</a></li>
<li class="chapter" data-level="8.2.7" data-path="references.html"><a href="references.html#r"><i class="fa fa-check"></i><b>8.2.7</b> R统计绘图</a></li>
<li class="chapter" data-level="8.2.8" data-path="references.html"><a href="references.html#section-8.2.8"><i class="fa fa-check"></i><b>8.2.8</b> 实验设计与技术</a></li>
<li class="chapter" data-level="8.2.9" data-path="references.html"><a href="references.html#section-8.2.9"><i class="fa fa-check"></i><b>8.2.9</b> 基础知识</a></li>
<li class="chapter" data-level="8.2.10" data-path="references.html"><a href="references.html#section-8.2.10"><i class="fa fa-check"></i><b>8.2.10</b> 必读综述</a></li>
<li class="chapter" data-level="8.2.11" data-path="references.html"><a href="references.html#section-8.2.11"><i class="fa fa-check"></i><b>8.2.11</b> 高分文章套路解读</a></li>
<li class="chapter" data-level="8.2.12" data-path="pythonbasic.html"><a href="pythonbasic.html#-"><i class="fa fa-check"></i><b>8.2.12</b> 科普视频-寓教于乐</a></li>
<li class="chapter" data-level="8.2.13" data-path="references.html"><a href="references.html#section-8.2.13"><i class="fa fa-check"></i><b>8.2.13</b> 友军文章汇总推荐</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="9" data-path="company-intro.html"><a href="company-intro.html"><i class="fa fa-check"></i><b>9</b> 公司简介</a></li>
<li class="divider"></li>
<li><a href="mailto:ct@ehbio.com" target="blank">ct@ehbio.com</a></li>

</ul>

      </nav>
    </div>

    <div class="book-body">
      <div class="body-inner">
        <div class="book-header" role="navigation">
          <h1>
            <i class="fa fa-circle-o-notch fa-spin"></i><a href="./">Python3学习教程</a>
          </h1>
        </div>

        <div class="page-wrapper" tabindex="-1" role="main">
          <div class="page-inner">

            <section class="normal" id="section-">
<div id="py3_ct" class="section level1">
<h1><span class="header-section-number">2</span> Python 教程</h1>
<p>陈同 (<a href="mailto:chentong_biology@163.com">chentong_biology@163.com</a>)</p>
<p>欢迎来到Python的世界，本教程将带你遨游<code>Python</code>，领悟<code>Python</code>的魅力。本教程专注于帮助初学者，尤其是生物信息分析人员快速学会<code>Python</code>的常用功能和使用方式，因此只精选了部分<code>Python</code>的功能，请额外参考Python经典教程<a href="http://www.byteofpython.info/">A byte of python</a>和它的<a href="http://woodpecker.org.cn/abyteofpython_cn/chinese/index.html">中文版</a> 来更好的理解<em>Python</em>. 本文档的概念和文字描述参考了A byte of python(中文版)，特此感谢。</p>
<p>本教程在<code>2017年12月25日</code>更新到<code>Python3</code>版本。</p>
<p>This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/2.0/">Creative Commons Attribution-NonCommercial-ShareAlike 2.0 Generic License</a>.</p>
<p>欢迎访问我们的视频课程 <a href="https://bioinfo.ke.qq.com" class="uri">https://bioinfo.ke.qq.com</a>。</p>
<div id="section-2.1" class="section level2">
<h2><span class="header-section-number">2.1</span> 背景介绍</h2>
<div id="section-2.1.1" class="section level3">
<h3><span class="header-section-number">2.1.1</span> 编程开篇</h3>
<p>A：最近在看什么书？</p>
<p>B：编程。</p>
<p>A：沈从文的那本啊。</p>
<p>B：……</p>
<p><img src="D:/project/GitHub/PBR_training/Image/biancheng.jpg"></img></p>
<hr />
<p>C：最近在学一门新语言，Python。</p>
<p>D：那是哪个国家的语言？</p>
<p>C：……</p>
</div>
<div id="python" class="section level3">
<h3><span class="header-section-number">2.1.2</span> 为什么学习Python</h3>
<ul>
<li><p>语法简单</p>
<p>Python语言写作的程序就像自然语言构建的伪代码一样，“所见即所想”。读<code>Python</code>代码就像读最简单的英文短文一样，写<code>Python</code>代码比写英文文章都要简单，“所想即所写”。很多刚学习<code>Python</code>的朋友都觉得很不可思议，原来怎么想怎么写出来就对了。</p></li>
<li><p>功能强大</p>
<p>现在程序语言的发展已经很成熟，每一种程序语言都能实现其它程序语言的全部功能。因此就程序语言本身来讲，功能都相差不大。<code>Python</code>语言的功能强大在于其活跃的社区和强大的第三方模块支持，使其作为科学计算的能力越来越强。</p></li>
<li><p>可扩展性好</p>
<p>能与C完美的融合，加快运行速度。可用加速模块有<code>Cython</code>, <code>PyPy</code>, <code>Pyrex</code>, <code>Psyco</code>等.</p></li>
</ul>
</div>
<div id="python" class="section level3">
<h3><span class="header-section-number">2.1.3</span> Python常用包</h3>
<ol style="list-style-type: decimal">
<li>科学计算 <code>Numpy</code>, <code>SciPy</code> (也是安装python包的拦路虎直到有了<a href="http://mp.weixin.qq.com/s/A4_j8ZbyprMr1TT_wgisQQ">conda</a>)</li>
<li>类比于R的数据框操作包 <a href="http://mp.weixin.qq.com/s/1h-_J2NKjD1KyymPAeHPOg">Pandas</a></li>
<li>可视化工具 <code>Seaborn</code> (配合pandas), <code>matplotlib</code> (类比MATLAB), <code>plotly</code> (交互式绘图), <code>ggplot</code> (类比ggplot2)</li>
<li>网站开发 <code>web.py</code>, <code>Django</code>, <code>Flask</code></li>
<li>任务调度和流程管理 <code>Airflow</code> (pipeline首选)</li>
<li>机器学习 <code>scikit-learn</code> (经典), <code>PyML</code>, <code>Tensorflow</code> (谷歌释放), <code>pylearn2</code>, <code>Orange</code> (图形界面的机器学习包)</li>
<li>网页抓取 <code>Beautiful Soup</code>，<code>requests</code>,</li>
<li>可重复编程 <code>Jupyter</code></li>
<li>正则表达式 <code>re</code></li>
</ol>
</div>
<div id="python" class="section level3">
<h3><span class="header-section-number">2.1.4</span> 怎么学习Python</h3>
<p>编程就像拼乐高，需要我们知道每个组分的特征以便在需要时可以使用，也需要脑袋中有个蓝图知道每一步要做什么，二者结合，就可以拼出你想要的世界。</p>
<p>在我看来，学习编程是<strong>学以致用</strong>，学习方式是<strong>硬着头皮</strong>去读，去写。</p>
<ul>
<li><p>多读经典书籍</p>
<p>首先从概念和理论上了解程序设计或Python程序设计，多读。书读百遍其义自见。</p></li>
<li><p>多做练习</p>
<p>任何练习题都可以，先易后难。如果能找到专业相关的，更好。</p></li>
<li><p>多读代码</p>
<p>多读优秀的代码，矫正自己的习惯和思维。</p></li>
</ul>
</div>
<div id="python" class="section level3">
<h3><span class="header-section-number">2.1.5</span> Python学习的几个阶段</h3>
<p><img src="coding_is_hard_confidence_competence.png" width="100%" style="display: block; margin: auto;" /></p>
<p>（图例“编程信心与能力”：纵轴为信心值，横轴为能力水平，虚线从左至右依次分割出手牵手蜜月期、混沌悬崖、绝望沙漠、令人兴奋的上升期四个阶段，第5条虚线标志着工作准备就绪）</p>
<ul>
<li><p>读文档是蜜月期，读读就过去，谁都会。</p></li>
<li><p>写程序是混沌悬崖，知道是这么回事，就是写不出来；</p></li>
<li><p>调程序是绝望沙漠，怎么看自己写的都对，就是编译器不开眼；</p></li>
<li><p>程序正确了就是兴奋期，万里长征迈出又一步。</p></li>
</ul>
</div>
<div id="python" class="section level3">
<h3><span class="header-section-number">2.1.6</span> 如何安装Python</h3>
<p>Python社区有很多功能很好的包，但逐个安装需要解决繁杂的依赖关系。通常我会推荐安装已经做好的集成包，一劳永逸的解决后续问题。<a href="https://store.continuum.io/cshop/anaconda/">Anaconda</a>是最优先推荐的分发包，集成了常用的数值计算、图形处理、可视化等工具包如<code>IPython</code>, <code>matplotlib</code>, <code>numpy</code>, <code>scipy</code>, 而且设定了更简单的安装Python模块的方法，可以节省大量的安装时间。</p>
<div id="python-" class="section level4">
<h4><span class="header-section-number">2.1.6.1</span> Python 常用包</h4>
<ol style="list-style-type: decimal">
<li>科学计算 <code>Numpy</code>, <code>SciPy</code> (也是安装python包的拦路虎直到有了<a href="http://mp.weixin.qq.com/s/A4_j8ZbyprMr1TT_wgisQQ">conda</a>)</li>
<li>类比于R的数据框操作包 <a href="http://mp.weixin.qq.com/s/1h-_J2NKjD1KyymPAeHPOg">Pandas</a></li>
<li>可视化工具 <code>Seaborn</code> (配合pandas), <code>matplotlib</code> (类比MATLAB), <code>plotly</code> (交互式绘图), <code>ggplot</code> (类比ggplot2)</li>
<li>网站开发 <code>web.py</code>, <code>Django</code>, <code>Flask</code></li>
<li>任务调度和流程管理 <code>Airflow</code> (pipeline首选)</li>
<li>机器学习 <code>scikit-learn</code> (经典), <code>PyML</code>, <code>Tensorflow</code> (谷歌释放), <code>pylearn2</code>, <code>Orange</code> (图形界面的机器学习包)</li>
<li>网页抓取 <code>Beautiful Soup</code>，<code>requests</code>,</li>
<li>可重复编程 <code>Jupyter</code></li>
<li>正则表达式 <code>re</code></li>
</ol>
</div>
</div>
<div id="python" class="section level3">
<h3><span class="header-section-number">2.1.7</span> 如何运行Python命令和脚本</h3>
<ul>
<li>对于初学者，本手册推荐直接在<code>Jupyter Notebook</code>下学习<code>Python</code>命令和脚本。我们这套教程也是用<code>Jupyter Notebook</code>写作而成，里面的代码可以随时修改和运行，并能同时记录你的脚本和输出，符合现在流行的“可重复性计算”的概念。
<ul>
<li>Linux/Unix用户直接在终端(Terminal)进入你的目标文件夹<code>cd /working_dir</code>[回车]，然后在终端输入<code>Jupyter notebook</code>[回车]即可启动<code>Jupyter notebook</code>。</li>
<li><p>Windows用户可以新建一个<code>Jupyter_notebook.bat</code>文件(新建一个txt文件，写入内容后修改后缀为<code>.bat</code>。若不能修改后缀，请Google搜索“Window是如何显示文件扩展名”)，并写入以下内容（注意把前两行的<em>盘符</em>和<em>路径</em>替换为你的工作目录），双击即可运行。</p>
<pre><code>D:
cd PBR_training
jupyter notebook
pause</code></pre></li>
<li><p><code>Jupyter notebook</code>启动后会打开默认的浏览器（需要在图形用户界面下工作），这时可以<code>新建</code>或<code>打开</code>相应路径下的ipynb文件。</p></li>
</ul></li>
<li>对于LInux或Unix用户，直接在终端输入 <code>python</code> 然后回车即可打开交互式<code>python</code>解释器，如下图所示。在这个解释器了敲入任何合法的<code>python</code>语句即可执行。此外，所有的命令还可以存储到一个文件一起执行，如下图所示。我们有一个包含<code>python</code>程序的文件<code>test.py</code>，我们只要在终端输入<code>python test.py</code>并回车就可以运行这个文件。同时我们也可在终端通过输入<code>chmod 755 test.py</code>赋予程序<code>test.py</code>可执行权限，并在终端输入<code>./test.py</code>运行<code>Python</code>脚本。更多Linux下的高级使用和Linux命令使用请见教程Bash_training-chinese.ipynb。</li>
</ul>
<p><img src="Python_start_run_linux.png" width="100%" style="display: block; margin: auto;" /></p>
<ul>
<li><p>对于Windows用户，可以通过“Windows键+R”调出“Run”窗口并输入“cmd”打开Windows命令解释器，输入<code>python</code>即可打开交互式<code>python</code>解释器。同时也可以双击安装后的软件的快捷方式打开图形界面的<code>Python</code>解释器，可以处理交互式命令和导入Python文件并执行。</p></li>
<li><p>对于交互式<code>Python</code>解释器，在使用结束后，通过键盘组合键<code>Ctrl-d</code> (Linux/Unix)或<code>Ctrl-z</code> (Windows)关闭。</p></li>
</ul>
</div>
<div id="python" class="section level3">
<h3><span class="header-section-number">2.1.8</span> 使用什么编辑器写Python脚本</h3>
<p>在你学成之后，可能主要操作都在服务器完成，而且日常工作一般会以脚本的形式解决。我个人推荐使用<a href="http://www.vim.org/download.php">Vim</a>来写作Python脚本。</p>
<p>Linux下<code>vim</code>的配置文件可从<a href="https://github.com/Tong-Chen/vim">我的 github</a>下载，Windows版可从<a href="http://pan.baidu.com/s/1kT5KIN1">我的百度云</a> 下载。</p>
</div>
</div>
<div id="python" class="section level2">
<h2><span class="header-section-number">2.2</span> Python程序事例</h2>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 假如我们有如下FASTA格式的文件，我们想把多行序列合并为一行，怎么做？</span>
<span class="cf">for</span> line <span class="op">in</span> <span class="bu">open</span>(<span class="st">&quot;data/test2.fa&quot;</span>):
    <span class="bu">print</span>(line.strip())</code></pre></div>
<pre><code>&gt;NM_001011874 gene=Xkr4 CDS=151-2091
gcggcggcgggcgagcgggcgctggagtaggagctggggagcggcgcggccggggaaggaagccagggcg
aggcgaggaggtggcgggaggaggagacagcagggacaggTGTCAGATAAAGGAGTGCTCTCCTCCGCTG
CCGAGGCATCATGGCCGCTAAGTCAGACGGGAGGCTGAAGATGAAGAAGAGCAGCGACGTGGCGTTCACC
CCGCTGCAGAACTCGGACAATTCGGGCTCTGTGCAAGGACTGGCTCCAGGCTTGCCGTCGGGGTCCGGAG
&gt;NM_001195662 gene=Rp1 CDS=55-909
AAGCTCAGCCTTTGCTCAGATTCTCCTCTTGATGAAACAAAGGGATTTCTGCACATGCTTGAGAAATTGC
AGGTCTCACCCAAAATGAGTGACACACCTTCTACTAGTTTCTCCATGATTCATCTGACTTCTGAAGGTCA
AGTTCCTTCCCCTCGCCATTCAAATATCACTCATCCTGTAGTGGCTAAACGCATCAGTTTCTATAAGAGT
GGAGACCCACAGTTTGGCGGCGTTCGGGTGGTGGTCAACCCTCGTTCCTTTAAGACTTTTGACGCTCTGC
TGGACAGTTTATCCAGGAAGGTACCCCTGCCCTTTGGGGTAAGGAACATCAGCACGCCCCGTGGACGACA
CAGCATCACCAGGCTGGAGGAGCTAGAGGACGGCAAGTCTTATGTGTGCTCCCACAATAAGAAGGTGCTG
&gt;NM_011283 gene=Rp1 CDS=128-6412
AATAAATCCAAAGACATTTGTTTACGTGAAACAAGCAGGTTGCATATCCAGTGACGTTTATACAGACCAC
ACAAACTATTTACTCTTTTCTTCGTAAGGAAAGGTTCAACTTCTGGTCTCACCCAAAATGAGTGACACAC
CTTCTACTAGTTTCTCCATGATTCATCTGACTTCTGAAGGTCAAGTTCCTTCCCCTCGCCATTCAAATAT
CACTCATCCTGTAGTGGCTAAACGCATCAGTTTCTATAAGAGTGGAGACCCACAGTTTGGCGGCGTTCGG
GTGGTGGTCAACCCTCGTTCCTTTAAGACTTTTGACGCTCTGCTGGACAGTTTATCCAGGAAGGTACCCC
TGCCCTTTGGGGTAAGGAACATCAGCACGCCCCGTGGACGACACAGCATCACCAGGCTGGAGGAGCTAGA
GGACGGCAAGTCTTATGTGTGCTCCCACAATAAGAAGGTGCTGCCAGTTGACCTGGACAAGGCCCGCAGG
CGCCCTCGGCCCTGGCTGAGTAGTCGCTCCATAAGCACGCATGTGCAGCTCTGTCCTGCAACTGCCAATA
TGTCCACCATGGCACCTGGCATGCTCCGTGCCCCAAGGAGGCTCGTGGTCTTCCGGAATGGTGACCCGAA
&gt;NM_0112835 gene=Rp1 CDS=128-6412
AATAAATCCAAAGACATTTGTTTACGTGAAACAAGCAGGTTGCATATCCAGTGACGTTTATACAGACCAC
ACAAACTATTTACTCTTTTCTTCGTAAGGAAAGGTTCAACTTCTGGTCTCACCCAAAATGAGTGACACAC
CTTCTACTAGTTTCTCCATGATTCATCTGACTTCTGAAGGTCAAGTTCCTTCCCCTCGCCATTCAAATAT
CACTCATCCTGTAGTGGCTAAACGCATCAGTTTCTATAAGAGTGGAGACCCACAGTTTGGCGGCGTTCGG
GTGGTGGTCAACCCTCGTTCCTTTAAGACTTTTGACGCTCTGCTGGACAGTTTATCCAGGAAGGTACCCC
TGCCCTTTGGGGTAAGGAACATCAGCACGCCCCGTGGACGACACAGCATCACCAGGCTGGAGGAGCTAGA
GGACGGCAAGTCTTATGTGTGCTCCCACAATAAGAAGGTGCTGCCAGTTGACCTGGACAAGGCCCGCAGG
CGCCCTCGGCCCTGGCTGAGTAGTCGCTCCATAAGCACGCATGTGCAGCTCTGTCCTGCAACTGCCAATA
TGTCCACCATGGCACCTGGCATGCTCCGTGCCCCAAGGAGGCTCGTGGTCTTCCGGAATGGTGACCCGAA</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aDict <span class="op">=</span> {}
<span class="cf">for</span> line <span class="op">in</span> <span class="bu">open</span>(<span class="st">&#39;data/test2.fa&#39;</span>):
    <span class="cf">if</span> line[<span class="dv">0</span>] <span class="op">==</span> <span class="st">&#39;&gt;&#39;</span>:
        key <span class="op">=</span> line.strip()
        aDict[key] <span class="op">=</span> []
    <span class="cf">else</span>:
        aDict[key].append(line.strip())
<span class="co">##------------------------------------------</span>
<span class="cf">for</span> key, valueL <span class="op">in</span> <span class="bu">list</span>(aDict.items()):
    <span class="bu">print</span>(key)
    <span class="bu">print</span>(<span class="st">&#39;&#39;</span>.join(valueL))</code></pre></div>
<pre><code>&gt;NM_001011874 gene=Xkr4 CDS=151-2091
gcggcggcgggcgagcgggcgctggagtaggagctggggagcggcgcggccggggaaggaagccagggcgaggcgaggaggtggcgggaggaggagacagcagggacaggTGTCAGATAAAGGAGTGCTCTCCTCCGCTGCCGAGGCATCATGGCCGCTAAGTCAGACGGGAGGCTGAAGATGAAGAAGAGCAGCGACGTGGCGTTCACCCCGCTGCAGAACTCGGACAATTCGGGCTCTGTGCAAGGACTGGCTCCAGGCTTGCCGTCGGGGTCCGGAG
&gt;NM_001195662 gene=Rp1 CDS=55-909
AAGCTCAGCCTTTGCTCAGATTCTCCTCTTGATGAAACAAAGGGATTTCTGCACATGCTTGAGAAATTGCAGGTCTCACCCAAAATGAGTGACACACCTTCTACTAGTTTCTCCATGATTCATCTGACTTCTGAAGGTCAAGTTCCTTCCCCTCGCCATTCAAATATCACTCATCCTGTAGTGGCTAAACGCATCAGTTTCTATAAGAGTGGAGACCCACAGTTTGGCGGCGTTCGGGTGGTGGTCAACCCTCGTTCCTTTAAGACTTTTGACGCTCTGCTGGACAGTTTATCCAGGAAGGTACCCCTGCCCTTTGGGGTAAGGAACATCAGCACGCCCCGTGGACGACACAGCATCACCAGGCTGGAGGAGCTAGAGGACGGCAAGTCTTATGTGTGCTCCCACAATAAGAAGGTGCTG
&gt;NM_011283 gene=Rp1 CDS=128-6412
AATAAATCCAAAGACATTTGTTTACGTGAAACAAGCAGGTTGCATATCCAGTGACGTTTATACAGACCACACAAACTATTTACTCTTTTCTTCGTAAGGAAAGGTTCAACTTCTGGTCTCACCCAAAATGAGTGACACACCTTCTACTAGTTTCTCCATGATTCATCTGACTTCTGAAGGTCAAGTTCCTTCCCCTCGCCATTCAAATATCACTCATCCTGTAGTGGCTAAACGCATCAGTTTCTATAAGAGTGGAGACCCACAGTTTGGCGGCGTTCGGGTGGTGGTCAACCCTCGTTCCTTTAAGACTTTTGACGCTCTGCTGGACAGTTTATCCAGGAAGGTACCCCTGCCCTTTGGGGTAAGGAACATCAGCACGCCCCGTGGACGACACAGCATCACCAGGCTGGAGGAGCTAGAGGACGGCAAGTCTTATGTGTGCTCCCACAATAAGAAGGTGCTGCCAGTTGACCTGGACAAGGCCCGCAGGCGCCCTCGGCCCTGGCTGAGTAGTCGCTCCATAAGCACGCATGTGCAGCTCTGTCCTGCAACTGCCAATATGTCCACCATGGCACCTGGCATGCTCCGTGCCCCAAGGAGGCTCGTGGTCTTCCGGAATGGTGACCCGAA
&gt;NM_0112835 gene=Rp1 CDS=128-6412
AATAAATCCAAAGACATTTGTTTACGTGAAACAAGCAGGTTGCATATCCAGTGACGTTTATACAGACCACACAAACTATTTACTCTTTTCTTCGTAAGGAAAGGTTCAACTTCTGGTCTCACCCAAAATGAGTGACACACCTTCTACTAGTTTCTCCATGATTCATCTGACTTCTGAAGGTCAAGTTCCTTCCCCTCGCCATTCAAATATCACTCATCCTGTAGTGGCTAAACGCATCAGTTTCTATAAGAGTGGAGACCCACAGTTTGGCGGCGTTCGGGTGGTGGTCAACCCTCGTTCCTTTAAGACTTTTGACGCTCTGCTGGACAGTTTATCCAGGAAGGTACCCCTGCCCTTTGGGGTAAGGAACATCAGCACGCCCCGTGGACGACACAGCATCACCAGGCTGGAGGAGCTAGAGGACGGCAAGTCTTATGTGTGCTCCCACAATAAGAAGGTGCTGCCAGTTGACCTGGACAAGGCCCGCAGGCGCCCTCGGCCCTGGCTGAGTAGTCGCTCCATAAGCACGCATGTGCAGCTCTGTCCTGCAACTGCCAATATGTCCACCATGGCACCTGGCATGCTCCGTGCCCCAAGGAGGCTCGTGGTCTTCCGGAATGGTGACCCGAA</code></pre>
</div>
<div id="python" class="section level2">
<h2><span class="header-section-number">2.3</span> Python语法</h2>
<div id="section-2.3.1" class="section level3">
<h3><span class="header-section-number">2.3.1</span> 层级缩进</h3>
<ul>
<li>合适的缩进。空白在Python中是很重要的，它称为缩进。在逻辑行首的空白（空格和制表符）用来决定逻辑行的缩进层次，从而用来决定语句的分组。这意味着同一层次的语句必须有相同的缩进。每一组这样的语句称为一个块。通常的缩进为4个空格, 在<code>Jupyter Notebook</code>中为一个<code>Tab</code>键。</li>
</ul>
<p>从下面这两个例子可以看出错误的缩进类型和对应的提示。 * “unexpected indent” 表示在不该出现空白的地方多了空白，并且指出问题出在第三行(line 3)。 * “expected an indented block” 表示应该有缩进的地方未缩进，也指出了问题所在行。 * “unindent does not match any outer indentation level” 表示缩进出现了不一致，问题通常会在指定行<strong>及其前面的行</strong>。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;不合适的缩进会引发错误，b前不该有的缩进&quot;</span>)
a <span class="op">=</span> <span class="st">&#39;No indent&#39;</span>
 b <span class="op">=</span> <span class="st">&#39;我前面有个空格……&#39;</span></code></pre></div>
<pre><code>  File &quot;&lt;ipython-input-2-ff110daefedf&gt;&quot;, line 3
    b = &#39;我前面有个空格……&#39;
    ^
IndentationError: unexpected indent</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;不合适的缩进，print是for的子语句，应该有缩进，却漏掉了&quot;</span>)
a <span class="op">=</span> [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>]

<span class="cf">for</span> i <span class="op">in</span> a:
<span class="bu">print</span> <span class="st">&quot;我应该被缩进，我从属于for循环!!!</span><span class="ch">\n</span><span class="st">&quot;</span></code></pre></div>
<pre><code>  File &quot;&lt;ipython-input-3-84bbc644895e&gt;&quot;, line 5
    print &quot;我应该被缩进，我从属于for循环!!!\n&quot;
        ^
IndentationError: expected an indented block</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> [<span class="dv">1</span>,<span class="dv">2</span>, <span class="dv">3</span>]
<span class="cf">if</span> a:
    <span class="cf">for</span> i <span class="op">in</span> a:
        <span class="bu">print</span>(i)
       <span class="bu">print</span>(i <span class="op">+</span> <span class="dv">1</span>, 
             <span class="st">&quot;为什么我的缩进跟其它行不一样呢，我的空格被谁吃了？&quot;</span>)
         <span class="bu">print</span>(i <span class="op">+</span> <span class="dv">1</span>, 
               <span class="st">&quot;为什么我的缩进跟其它行不一样呢，谁给了我个空格？&quot;</span>)</code></pre></div>
<pre><code>  File &quot;&lt;tokenize&gt;&quot;, line 5
    print(i + 1,
    ^
IndentationError: unindent does not match any outer indentation level</code></pre>
</div>
<div id="python" class="section level3">
<h3><span class="header-section-number">2.3.2</span> Python作为计算器的使用</h3>
<p>Python中可以进行基本的数学运算，与小学中学过的一样，加减乘除取余数等，需要注意的是运算符的优先级。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">2</span> <span class="op">+</span> <span class="dv">2</span></code></pre></div>
<pre><code>4</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">2</span> <span class="op">+</span> <span class="dv">3</span> <span class="op">+</span><span class="dv">5</span></code></pre></div>
<pre><code>10</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">2</span> <span class="op">+</span> <span class="dv">3</span> <span class="op">*</span> <span class="dv">5</span> </code></pre></div>
<pre><code>17</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">(<span class="dv">2</span> <span class="op">+</span> <span class="dv">3</span>) <span class="op">*</span> <span class="dv">5</span></code></pre></div>
<pre><code>25</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 整除</span>
<span class="dv">23</span> <span class="op">//</span> <span class="dv">7</span></code></pre></div>
<pre><code>3</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 取余数</span>
<span class="dv">23</span> <span class="op">%</span> <span class="dv">7</span></code></pre></div>
<pre><code>2</code></pre>
<div id="section-2.3.2.1" class="section level4">
<h4><span class="header-section-number">2.3.2.1</span> 第一个小程序</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;Hello, Python!&quot;</span>)</code></pre></div>
<pre><code>Hello, Python!</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">myname <span class="op">=</span> <span class="bu">input</span>(<span class="st">&quot;Your name: &quot;</span>)
<span class="bu">print</span>(<span class="st">&quot;Hello&quot;</span>, myname)</code></pre></div>
<pre><code>Your name: CT
Hello CT</code></pre>
</div>
</div>
<div id="section-2.3.3" class="section level3">
<h3><span class="header-section-number">2.3.3</span> 变量、数据结构、流程控制</h3>
<p>我们先看一个动图展示内存中变量的赋值、存储、值的改变和程序的运行。</p>
<p>点击访问动图 <a href="http://www.ehbio.com/ehbio_resource/python_tutor.gif" class="uri">http://www.ehbio.com/ehbio_resource/python_tutor.gif</a></p>
<ul>
<li><p>常量，指固定的数字或字符串，如<code>2</code>, <code>2.9</code>, <code>&quot;Hello world&quot;</code>等。</p></li>
<li>变量，存储了数字或字符串的事物称为变量，它可以被赋值或被修改。简单的可以理解为变量是一个盒子，你可以把任何东西放在里面，通过盒子的名字来取出盒子内的东西。
<ul>
<li>数值变量：存储了数的变量。<br />
</li>
<li>字符串变量：存储了字符串的变量。字符串变量的名字最好不为<code>str</code>，可以使用<code>aStr</code>。</li>
<li>列表 (list): list是处理一组<em>有序</em>项目的数据结构，即你可以在一个列表中存储一个 <em>序列</em> 的项目。假想你有一个购物列表，上面记载着你要买的东西，你就容易理解列表了。只不过在你的购物表上，可能每样东西都独自占有一行，而在Python中，你在每个项目之间用逗号分割。列表中的项目应该包括在<strong>方括号</strong>中，这样Python就知道你是在指明一个列表。一旦你创建了一个列表，你可以添加、删除或是搜索列表中的项目。由于你可以增加或删除项目，我们说列表是 <em>可变的</em> 数据类型，即这种类型是可以被改变的。列表变量的名字最好不为<code>list</code>，可以使用<code>aList</code>。</li>
<li>元祖 (tuple)：元组和列表十分类似，但是不可修改。元组通过<strong>圆括号中用逗号分割的项目</strong>定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候，即被使用的元组的值不会改变。元组变量的名字最好不为<code>tuple</code>，可以使用<code>aTuple</code>。</li>
<li>集合 (Set)：也与列表类似，但是元素不可重复。通常用来去除重复、求交集、并集等。而且集合的查询速度远远快于列表，可以用来提高运算速度。</li>
<li>字典 (dict): 字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿，即，我们把键（名字）和值（详细情况）联系在一起。注意，键必须是唯一的，就像如果有两个人恰巧同名的话，你无法找到正确的信息。多个键可以指向同一个值。当一个键需要指向多个值时，这些值需要放在列表、元组或字典里面。注意，你只能使用不可变的对象（字符串，数字，元组）来作为字典的键，但是可以用不可变或可变的对象作为字典的值。键值对在字典中以这样的方式标记：d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割，而各个对用逗号分割，所有这些都包括在<strong>花括号</strong>中。记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序，那么你应该在使用前自己对它们排序。列表变量的名字最好不为<code>dict</code>，可以使用<code>aDict</code>。</li>
<li>序列：列表、元组、字符串都是一种序列格式。同时还可以使用range来产生序列。序列的两个主要操作时<em>索引操作</em>和<em>切片操作</em>。</li>
</ul></li>
<li>标示符
<ul>
<li>变量的名字被称为标示符。标识符对大小写敏感，第一个字符必须是字母表中的字母（大写或小写）或者一个下划线（_），其它部分额外包含数字。有效的标示符有: <code>abc</code>, <code>_abc</code>, <code>a_b_2</code>, <code>__23</code>等。无效的标示符有: <code>2a</code>, <code>3b</code>。</li>
<li>标示符最好不使用Python内置的关键字，如<code>str</code>, <code>list</code>, <code>int</code>, <code>def</code>, <code>split</code>, <code>dict</code>等。</li>
<li>标示符最好能言词达意，即展示变量的类型，又带有变量的实际含义。如<code>line</code>表示文件的一行，<code>lineL</code>表示存有从文件读入的每一行的列表。</li>
</ul></li>
<li>控制流
<ul>
<li><code>if</code>语句</li>
</ul>
<p><code>if</code>语句用来检验一个条件，如果条件为真，我们运行一块语句（称为 <code>if-块</code>），否则我们处理另外一块语句（称为 <code>else-块</code>）。<code>else</code> 从句是可选的。如果有多个条件，中间使用<code>elif</code>。</p>
<p>举个例子：“买五个包子，如果看到卖西瓜的，买一个”——最后程序猿买了一个包子” <code>买包子 = 5   if 看到卖西瓜的:       买包子 = 1</code></p>
<ul>
<li><code>For</code>语句</li>
</ul>
<p>for..in是一个循环语句，它在一序列的对象上递归,即逐一使用队列中的每个项目。</p>
<ul>
<li><code>While</code>语句</li>
</ul>
<p>只要在一个条件为真的情况下，<code>while</code>语句允许你重复执行一块语句。<code>while</code>语句是所谓 <em>循环</em> 语句的一个例子。<code>while</code>语句有一个可选的<code>else</code>从句。</p>
<ul>
<li><code>break</code>语句是用来 <em>终止</em> 循环语句的，即哪怕循环条件没有成为False或序列还没有被完全递归，也停止执行循环语句。</li>
</ul>
<p>一个重要的注释是，如果你从<code>for</code>或<code>while</code>循环中 <em>终止</em> ，任何对应的循环else块将不执行。</p>
<ul>
<li><p><code>continue</code>语句被用来告诉<code>Python</code>跳过当前循环块中的剩余语句，然后 <em>继续</em> 进行下一轮循环。</p></li>
<li><p>逻辑运算符 <code>and</code>, <code>or</code>, <code>not</code>。</p></li>
</ul></li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 变量名命名:为清晰表达，驼峰式，下划线式</span>
LookLikeThis <span class="op">=</span> <span class="dv">1</span>
look_like_this <span class="op">=</span> <span class="st">&#39;a&#39;</span></code></pre></div>
<div id="pythonintfloatstr-1" class="section level4">
<h4><span class="header-section-number">2.3.3.1</span> Python中的数据类型：整数（int）、浮点（float）和字符串（str）</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">type</span>(<span class="dv">2</span>)</code></pre></div>
<pre><code>int</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">type</span>(<span class="fl">2.5</span>)</code></pre></div>
<pre><code>float</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">type</span>(<span class="st">&quot;Hello, everyone&quot;</span>)</code></pre></div>
<pre><code>str</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">type</span>([<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>])</code></pre></div>
<pre><code>list</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 类型转换函数</span>
<span class="bu">str</span>()
<span class="bu">int</span>()
<span class="bu">float</span>()</code></pre></div>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">str</span>(<span class="dv">2</span>)</code></pre></div>
<pre><code>&#39;2&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 字符和数字不同</span>
<span class="dv">42</span> <span class="op">!=</span> <span class="st">&quot;42&quot;</span></code></pre></div>
<pre><code>True</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">42</span> <span class="op">==</span> <span class="bu">int</span>(<span class="st">&quot;42&quot;</span>)</code></pre></div>
<pre><code>True</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## This is my first python program！</span>

myName <span class="op">=</span> <span class="bu">input</span>(<span class="st">&quot;Hello, what is your name?&quot;</span>)
<span class="bu">print</span>(<span class="st">&#39;It is  good to meet you,&#39;</span> <span class="op">+</span> myName)
<span class="bu">print</span>(<span class="st">&#39;The length of your name is&#39;</span>, <span class="bu">str</span>(<span class="bu">len</span>(myName)))

myAge <span class="op">=</span> <span class="bu">input</span>(<span class="st">&#39;What is your age?&#39;</span>)
<span class="bu">print</span>(<span class="st">&#39;You will be &#39;</span> <span class="op">+</span> <span class="bu">str</span>(<span class="bu">int</span>(myAge) <span class="op">+</span> <span class="dv">1</span>) <span class="op">+</span> <span class="st">&#39; in a year.&#39;</span>)</code></pre></div>
<pre><code>Hello, what is your name?CT
It is  good to meet you,CT
The length of your name is 2
What is your age?20
You will be 21 in a year.</code></pre>
</div>
<div id="section-2.3.3.2" class="section level4">
<h4><span class="header-section-number">2.3.3.2</span> 逻辑值和比较操作</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="va">False</span>
a</code></pre></div>
<pre><code>False</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">b <span class="op">=</span> <span class="va">True</span>
b</code></pre></div>
<pre><code>True</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="st">&quot;False&quot;</span>
a</code></pre></div>
<pre><code>&#39;False&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">42</span> <span class="op">==</span> <span class="dv">40</span></code></pre></div>
<pre><code>False</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">42</span> <span class="op">==</span> <span class="st">&quot;42&quot;</span></code></pre></div>
<pre><code>False</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">30</span> <span class="op">==</span> <span class="dv">30</span></code></pre></div>
<pre><code>True</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 注意赋值(一个=)和比较(==)的区别</span>
a <span class="op">=</span> <span class="st">&#39;hello&#39;</span>

a <span class="op">==</span> <span class="st">&#39;hello&#39;</span></code></pre></div>
<pre><code>True</code></pre>
<div id="and-or-not" class="section level5">
<h5><span class="header-section-number">2.3.3.2.1</span> 布尔操作符<code>and</code>, <code>or</code>, <code>not</code></h5>
<ul>
<li>逻辑与 <code>and</code>：所有为真才为真</li>
<li>逻辑或 <code>or</code>：所有为假才为假</li>
<li>逻辑非 <code>not</code>: 真变假，假变真</li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">(<span class="dv">3</span> <span class="op">&gt;</span> <span class="dv">2</span>) <span class="op">and</span> (<span class="dv">5</span> <span class="op">&lt;</span> <span class="dv">6</span>)</code></pre></div>
<pre><code>True</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">(<span class="dv">3</span> <span class="op">&lt;</span> <span class="dv">2</span>) <span class="op">or</span> (<span class="dv">5</span> <span class="op">&lt;</span> <span class="dv">6</span>)</code></pre></div>
<pre><code>True</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">not</span> <span class="va">True</span></code></pre></div>
<pre><code>False</code></pre>
</div>
</div>
<div id="-1" class="section level4">
<h4><span class="header-section-number">2.3.3.3</span> 控制流</h4>
<p>if 条件（True or False） ：</p>
<pre><code>代码块1</code></pre>
<p>elif 条件 ：</p>
<pre><code>代码块</code></pre>
<p>else ：</p>
<pre><code>代码块2</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">##条件</span>
name <span class="op">=</span> <span class="bu">input</span>(<span class="st">&#39;Please enter a name and click Enter</span><span class="ch">\n</span><span class="st">&#39;</span>)
<span class="cf">if</span> name <span class="op">==</span> <span class="st">&#39;ehbio&#39;</span>:
    <span class="bu">print</span> (<span class="st">&#39;hello ehbio&#39;</span>)
<span class="cf">else</span> :
    <span class="bu">print</span> (<span class="st">&#39;You are not ehbio&#39;</span>)</code></pre></div>
<pre><code>Please enter a name and click Enter
CT
You are not ehbio</code></pre>
</div>
<div id="while-1" class="section level4">
<h4><span class="header-section-number">2.3.3.4</span> While循环</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="dv">0</span>
<span class="cf">while</span> a <span class="op">&lt;</span> <span class="dv">5</span>:
    <span class="bu">print</span>(<span class="st">&#39;Hello, world&#39;</span>)
    a <span class="op">=</span> a <span class="op">+</span> <span class="dv">1</span></code></pre></div>
<pre><code>Hello, world
Hello, world
Hello, world
Hello, world
Hello, world</code></pre>
</div>
<div id="section-2.3.3.5" class="section level4">
<h4><span class="header-section-number">2.3.3.5</span> 数值变量操作</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;数值变量&quot;</span>)
a <span class="op">=</span> <span class="dv">5</span>   <span class="co">#注意等号两边的空格，为了易于辨识，操作符两侧最好有空格，数量不限</span>
<span class="bu">print</span>(a)

<span class="bu">print</span>()
<span class="bu">print</span>(<span class="st">&quot;The type of a is&quot;</span>, <span class="bu">type</span>(a))

<span class="co">##print &quot;这是保留节目，通常判断变量的类型使用的不是type是isinstance.&quot;</span>
<span class="co">##print &quot;a is an int, &quot;, isinstance(a,int)</span>

<span class="co">## 再次赋值就是覆盖</span>
a <span class="op">=</span> <span class="dv">6</span>
<span class="bu">print</span>(a)</code></pre></div>
<pre><code>数值变量
5

The type of a is &lt;class &#39;int&#39;&gt;
6</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 判断</span>
<span class="bu">print</span>(<span class="st">&quot;比较数值的大小&quot;</span>)
a <span class="op">=</span> <span class="dv">5</span>

<span class="co">## 注意大于号两边的空格，为了易于辨识，操作符两侧最好有空格，数量不限</span>
<span class="cf">if</span> a <span class="op">&gt;</span> <span class="dv">4</span>:
    <span class="bu">print</span>(<span class="st">&quot;a is larger than 4.&quot;</span>)
<span class="cf">elif</span> a <span class="op">==</span> <span class="dv">4</span>:
    <span class="bu">print</span>(<span class="st">&quot;a is equal to 4.&quot;</span>)
<span class="cf">else</span>:
    <span class="bu">print</span>(<span class="st">&quot;a is less than 4&quot;</span>)</code></pre></div>
<pre><code>比较数值的大小
a is larger than 4.</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;给定数值变量a和b的值，通过判断和重新赋值使得a的值小，b的值大&quot;</span>)
a <span class="op">=</span> <span class="dv">5</span>
b <span class="op">=</span> <span class="dv">3</span>

<span class="cf">if</span> a <span class="op">&gt;</span> b:
    a,b <span class="op">=</span> b,a
<span class="co">##-------------------</span>
<span class="bu">print</span>(a)
<span class="bu">print</span>(b)</code></pre></div>
<pre><code>给定数值变量a和b的值，通过判断和重新赋值使得a的值小，b的值大
3
5</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&#39;&#39;&#39;#数值运算, 符合传统的优先级，需要使用括号来改变优先级，</span>
<span class="st">和小学学的数学一模一样！！&#39;&#39;&#39;</span>)
a <span class="op">=</span> <span class="dv">5</span>
b <span class="op">=</span> <span class="dv">3</span>

<span class="bu">print</span>(<span class="st">&quot;a + b =&quot;</span>, a <span class="op">+</span> b)
<span class="bu">print</span>(<span class="st">&quot;a * b =&quot;</span>, a <span class="op">*</span> b)
<span class="bu">print</span>(<span class="st">&quot;a / b =&quot;</span>, a <span class="op">/</span> b)  <span class="co"># 1</span>
<span class="bu">print</span>(<span class="st">&quot;2 * (a+b) =&quot;</span>, <span class="dv">2</span> <span class="op">*</span> (a <span class="op">+</span> b))
<span class="bu">print</span>(<span class="st">&quot;取余数： a % b =&quot;</span>, a <span class="op">%</span> b)
<span class="bu">print</span>(<span class="st">&quot;取余数是很好的判断循环的地方，因为每个固定的周期余数就会循环一次&quot;</span>)</code></pre></div>
<pre><code>#数值运算, 符合传统的优先级，需要使用括号来改变优先级，
和小学学的数学一模一样！！
a + b = 8
a * b = 15
a / b = 1.6666666666666667
2 * (a+b) = 16
取余数： a % b = 2
取余数是很好的判断循环的地方，因为每个固定的周期余数就会循环一次</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">3</span> <span class="op">/</span> <span class="dv">0</span></code></pre></div>
<pre><code>---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

&lt;ipython-input-17-2b706ee9dd8e&gt; in &lt;module&gt;()
----&gt; 1 3 / 0


ZeroDivisionError: division by zero</code></pre>
</div>
<div id="section-2.3.3.6" class="section level4">
<h4><span class="header-section-number">2.3.3.6</span> 字符串变量操作</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;字符串变量&quot;</span>)

<span class="co">## 注意引号的配对</span>
a <span class="op">=</span> <span class="st">&quot;Hello, welcome to Python&quot;</span>

<span class="co">##a = 123</span>
<span class="co">##a = str(a)</span>

<span class="bu">print</span>(<span class="st">&quot;The string a is:&quot;</span>, a)
<span class="bu">print</span>()

<span class="co">## 占位符</span>
<span class="bu">print</span>(<span class="st">&quot;The length of this string &lt;</span><span class="sc">%s</span><span class="st">&gt; is </span><span class="sc">%d</span><span class="st">&quot;</span> <span class="op">%</span> (a, <span class="bu">len</span>(a)))
<span class="bu">print</span>()

<span class="bu">print</span>(<span class="st">&quot;The type of a is&quot;</span>, <span class="bu">type</span>(a))</code></pre></div>
<pre><code>字符串变量
The string a is: Hello, welcome to Python

The length of this string &lt;Hello, welcome to Python&gt; is 24

The type of a is &lt;class &#39;str&#39;&gt;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="st">&quot;大事赖独断而不赖众谋&quot;</span>
<span class="bu">print</span>(<span class="st">&quot;The string a is:&quot;</span>, a)
<span class="bu">print</span>()

<span class="co">## len函数：获得字符串长度</span>
<span class="bu">print</span>(<span class="st">&quot;The length of this string &lt;</span><span class="sc">%s</span><span class="st">&gt; is </span><span class="sc">%d</span><span class="st">&quot;</span> <span class="op">%</span> (a, <span class="bu">len</span>(a)))
<span class="bu">print</span>()</code></pre></div>
<pre><code>The string a is: 大事赖独断而不赖众谋

The length of this string &lt;大事赖独断而不赖众谋&gt; is 10</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="st">&quot;Hello, welcome to Python&quot;</span>

<span class="bu">print</span>(<span class="st">&quot;取出字符串的第一个字符、最后一个字符、中间部分字符&quot;</span>)
<span class="bu">print</span>(<span class="st">&quot;The first character of a is </span><span class="sc">%s</span><span class="ch">\n</span><span class="st">&quot;</span> <span class="op">%</span> a[<span class="dv">0</span>])

<span class="bu">print</span>(<span class="st">&quot;The first five characters of a are </span><span class="sc">%s</span><span class="ch">\n</span><span class="st">&quot;</span> <span class="op">%</span> a[<span class="dv">0</span>:<span class="dv">5</span>])

<span class="bu">print</span>(<span class="st">&quot;The last character of a is </span><span class="sc">%s</span><span class="ch">\n</span><span class="st">&quot;</span> <span class="op">%</span> a[<span class="op">-</span><span class="dv">1</span>])
<span class="bu">print</span>(<span class="st">&quot;The last two characters of a are </span><span class="sc">%s</span><span class="ch">\n</span><span class="st">&quot;</span> <span class="op">%</span> a[<span class="op">-</span><span class="dv">2</span>:])
<span class="bu">print</span>(<span class="st">&quot;The last character of a is </span><span class="sc">%s</span><span class="ch">\n</span><span class="st">&quot;</span> <span class="op">%</span> a[<span class="bu">len</span>(a) <span class="op">-</span> <span class="dv">1</span>])
<span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">这部分很重要啊，字符串的索引和切片操作是及其常用的。&quot;</span>)</code></pre></div>
<pre><code>取出字符串的第一个字符、最后一个字符、中间部分字符
The first character of a is H

The first five characters of a are Hello

The last character of a is n

The last two characters of a are on

The last character of a is n


这部分很重要啊，字符串的索引和切片操作是及其常用的。</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="st">&quot;oaoaoaoa&quot;</span>

<span class="bu">print</span>(<span class="st">&quot;遍历字符串&quot;</span>)
<span class="cf">for</span> i <span class="op">in</span> a:
    <span class="bu">print</span>(i)

<span class="bu">print</span>()
<span class="bu">print</span>(<span class="st">&quot;The index of first &lt;o&gt; is: &quot;</span>,a.find(<span class="st">&#39;o&#39;</span>))
<span class="bu">print</span>(<span class="st">&quot;The index of first &lt;c&gt; is: &quot;</span>,a.find(<span class="st">&#39;c&#39;</span>))
    
<span class="bu">print</span>(<span class="st">&quot;输出符合特定要求的字符的位置&quot;</span>)
<span class="bu">print</span>()
pos <span class="op">=</span> <span class="dv">0</span>
<span class="cf">for</span> i <span class="op">in</span> a:
    pos <span class="op">+=</span> <span class="dv">1</span>
    <span class="cf">if</span> i <span class="op">==</span> <span class="st">&#39;o&#39;</span>:
        <span class="bu">print</span>(pos)
    <span class="co">#-------------------</span>
<span class="co">##-----------------------</span>
<span class="bu">print</span>(<span class="st">&#39;&#39;&#39;</span><span class="ch">\n</span><span class="st">知道吗？不经意间我们写出了Python的</span>
<span class="st">一个内置的标准函数find或者index,而且功能还更强大&#39;&#39;&#39;</span>)

<span class="bu">print</span>(<span class="st">&#39;&#39;&#39;</span><span class="ch">\n</span><span class="st">自己尝试实现程序语言内建的函数是学习程序语言</span>
<span class="st">的很好方法。&#39;&#39;&#39;</span>)</code></pre></div>
<pre><code>遍历字符串
o
a
o
a
o
a
o
a

The index of first &lt;o&gt; is:  0
The index of first &lt;c&gt; is:  -1
输出符合特定要求的字符的位置

1
3
5
7

知道吗？不经意间我们写出了Python的
一个内置的标准函数find或者index,而且功能还更强大

自己尝试实现程序语言内建的函数是学习程序语言
的很好方法。</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;我们看看用内置函数如何找到所有 o 的位置</span><span class="ch">\n</span><span class="st">&quot;</span>)
a <span class="op">=</span> <span class="st">&quot;oaoaoaoa&quot;</span>

<span class="bu">print</span>(<span class="st">&quot;内置函数find只能确定最先出现的 o 的位置&quot;</span>)
pos <span class="op">=</span> a.find(<span class="st">&#39;o&#39;</span>)

<span class="bu">print</span>(<span class="st">&quot;因此，我们要在发现 o 之后，截取其后的字符串，再执行find操作&quot;</span>)
<span class="cf">while</span> <span class="dv">1</span>:
    <span class="bu">print</span>(pos <span class="op">+</span> <span class="dv">1</span>)
    new <span class="op">=</span> a[pos <span class="op">+</span> <span class="dv">1</span>:].find(<span class="st">&#39;o&#39;</span>)
    <span class="cf">if</span> new <span class="op">==</span> <span class="op">-</span><span class="dv">1</span>:
        <span class="cf">break</span>
    pos <span class="op">=</span> new <span class="op">+</span> pos <span class="op">+</span> <span class="dv">1</span>
<span class="co">## help(str)</span></code></pre></div>
<pre><code>我们看看用内置函数如何找到所有 o 的位置

内置函数find只能确定最先出现的 o 的位置
因此，我们要在发现 o 之后，截取其后的字符串，再执行find操作
1
3
5
7</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>()
<span class="bu">print</span>(<span class="st">&quot;利用split分割字符串</span><span class="ch">\n</span><span class="st">&quot;</span>)
str1 <span class="op">=</span> <span class="st">&quot;a b c d e f g&quot;</span>
strL <span class="op">=</span> str1.split(<span class="st">&#39; &#39;</span>)
<span class="bu">print</span>(strL)
<span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">使用split命令就可以把字符串分成列表了，想取用哪一列都随便你了。&quot;</span>)
<span class="co">## 使用下面的命令查看可以对字符串进行的操作</span>
<span class="co">## help(str)</span></code></pre></div>
<pre><code>利用split分割字符串

[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;]

使用split命令就可以把字符串分成列表了，想取用哪一列都随便你了。</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;字符串的连接</span><span class="ch">\n</span><span class="st">&quot;</span>)

a <span class="op">=</span> <span class="st">&quot;Hello&quot;</span>
b <span class="op">=</span> <span class="st">&quot;Python&quot;</span>
c <span class="op">=</span> a <span class="op">+</span> <span class="st">&#39;, &#39;</span> <span class="op">+</span> b
<span class="bu">print</span>(c)
<span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">原来字符串相加就可以连起来啊！</span><span class="ch">\n</span><span class="st">&quot;</span>)
<span class="bu">print</span>(<span class="st">&#39;&#39;&#39;注意，这不是连接字符串最好的方式。</span>
<span class="st">考虑到字符串是不可修改的，每次连接操作都是新开辟一个内存空间，</span>
<span class="st">把字符串存到里面，这样的连接操作执行几十万次会很影响运行速度。&#39;&#39;&#39;</span>)</code></pre></div>
<pre><code>字符串的连接

Hello, Python

原来字符串相加就可以连起来啊！

注意，这不是连接字符串最好的方式。
考虑到字符串是不可修改的，每次连接操作都是新开辟一个内存空间，
把字符串存到里面，这样的连接操作执行几十万次会很影响运行速度。</code></pre>
<p>关于字符串链接为什么不推荐使用 <code>+</code>，文章<a href="https://mp.weixin.qq.com/s/n5kkZfC8FGlzeBODarLHcw">为啥我的Python这么慢 (一)</a>给出了一个很好的演示例子。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&#39;&#39;&#39;去除字符串中特定的字符。通常我们在文件中读取的一行都包含换行符，</span>
<span class="st">linux下为</span><span class="ch">\\</span><span class="st">n </span><span class="ch">\n</span><span class="st">&#39;&#39;&#39;</span>)  <span class="co"># \\转义字符</span>

a <span class="op">=</span> <span class="st">&quot;oneline</span><span class="ch">\n</span><span class="st">&quot;</span>
<span class="bu">print</span>(<span class="st">&quot;Currently, the string &lt;a&gt; is **&quot;</span>, a, <span class="st">&quot;**. \</span>
<span class="ch">\n</span><span class="st"> The length of string &lt;a&gt; is **&quot;</span>, <span class="bu">len</span>(a), <span class="st">&quot;**. \</span>
<span class="ch">\n</span><span class="st"> 我为什么换到下一行了？</span><span class="ch">\n</span><span class="st">&quot;</span>)

a <span class="op">=</span> a.strip()
<span class="bu">print</span>(<span class="st">&quot;Currently, the string &lt;a&gt; is **&quot;</span>, a, <span class="st">&quot;**. \</span>
<span class="ch">\n</span><span class="st"> The length of string &lt;a&gt; is **&quot;</span>, <span class="bu">len</span>(a), <span class="st">&quot;**. \</span>
<span class="ch">\n</span><span class="st"> 删掉了换行符后，少了个字符，而且没换行！</span><span class="ch">\n</span><span class="st">&quot;</span>)

a <span class="op">=</span> a.strip(<span class="st">&#39;o&#39;</span>)
<span class="bu">print</span>(<span class="st">&quot;Currently, the string &lt;a&gt; is **&quot;</span>, a, <span class="st">&quot;**. \</span>
<span class="ch">\n</span><span class="st"> The length of string &lt;a&gt; is **&quot;</span>, <span class="bu">len</span>(a), <span class="st">&quot;**. \</span>
<span class="st">又少了个字符！！</span><span class="ch">\n</span><span class="st">&quot;</span>)

a <span class="op">=</span> a.strip(<span class="st">&#39;one&#39;</span>)
<span class="bu">print</span>(<span class="st">&quot;Currently, the string &lt;a&gt; is **&quot;</span>, a, <span class="st">&quot;**. \</span>
<span class="ch">\n</span><span class="st"> The length of string &lt;a&gt; is **&quot;</span>, <span class="bu">len</span>(a), <span class="st">&quot;**. \</span>
<span class="st">又少字符了！！</span><span class="ch">\n</span><span class="st">&quot;</span>)</code></pre></div>
<pre><code>去除字符串中特定的字符。通常我们在文件中读取的一行都包含换行符，
linux下为\n 

Currently, the string &lt;a&gt; is ** oneline
 **. 
 The length of string &lt;a&gt; is ** 8 **. 
 我为什么换到下一行了？

Currently, the string &lt;a&gt; is ** oneline **. 
 The length of string &lt;a&gt; is ** 7 **. 
 删掉了换行符后，少了个字符，而且没换行！

Currently, the string &lt;a&gt; is ** neline **. 
 The length of string &lt;a&gt; is ** 6 **. 又少了个字符！！

Currently, the string &lt;a&gt; is ** li **. 
 The length of string &lt;a&gt; is ** 2 **. 又少字符了！！</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;字符串的替换</span><span class="ch">\n</span><span class="st">&quot;</span>)

a <span class="op">=</span> <span class="st">&quot;Hello, Python&quot;</span>
b <span class="op">=</span> a.replace(<span class="st">&quot;Hello&quot;</span>, <span class="st">&quot;Welcome&quot;</span>)
<span class="bu">print</span>(<span class="st">&quot;原始字符串是:&quot;</span>, a)
<span class="bu">print</span>()
<span class="bu">print</span>(<span class="st">&quot;替换后的字符串是:&quot;</span>, b)
<span class="bu">print</span>()

c <span class="op">=</span> a.replace(<span class="st">&quot;o&quot;</span>, <span class="st">&quot;O&quot;</span>)
<span class="bu">print</span>(c)
<span class="bu">print</span>(<span class="st">&quot;所有的o都被替换了！</span><span class="ch">\n</span><span class="st">&quot;</span>)

<span class="bu">print</span>(<span class="st">&quot;如果我只替换第一个o怎么办呢？</span><span class="ch">\n</span><span class="st">&quot;</span>)
c <span class="op">=</span> a.replace(<span class="st">&quot;o&quot;</span>, <span class="st">&quot;O&quot;</span>, <span class="dv">1</span>)
<span class="bu">print</span>(c)</code></pre></div>
<pre><code>字符串的替换

原始字符串是: Hello, Python

替换后的字符串是: Welcome, Python

HellO, PythOn
所有的o都被替换了！

如果我只替换第一个o怎么办呢？

HellO, Python</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 中文替换也可以</span>
a <span class="op">=</span> <span class="st">&quot;忙处事为，常向闲中先检点，过举自稀；动时念想，预从静里密操持，非心自息。&quot;</span>
<span class="bu">print</span>(a.replace(<span class="st">&#39;；&#39;</span>, <span class="st">&#39;</span><span class="ch">\n</span><span class="st">&#39;</span>))</code></pre></div>
<pre><code>忙处事为，常向闲中先检点，过举自稀
动时念想，预从静里密操持，非心自息。</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;字符串帮助，查看字符串可用方法&quot;</span>)
<span class="bu">help</span>(<span class="bu">str</span>)</code></pre></div>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;大小写判断和转换&quot;</span>)
a <span class="op">=</span> <span class="st">&#39;Sdsdsd&#39;</span>
<span class="bu">print</span>(<span class="st">&quot;All elements in &lt;</span><span class="sc">%s</span><span class="st">&gt; is lowercase: </span><span class="sc">%s</span><span class="st">&quot;</span> <span class="op">%</span> (a, a.islower()))
<span class="bu">print</span>(<span class="st">&quot;Transfer all elments in &lt;</span><span class="sc">%s</span><span class="st">&gt; to lowerse &lt;</span><span class="sc">%s</span><span class="st">&gt;&quot;</span> <span class="op">%</span> (a, a.lower()))
<span class="bu">print</span>(<span class="st">&quot;Transfer all elments in &lt;</span><span class="sc">%s</span><span class="st">&gt; to upperse &lt;</span><span class="sc">%s</span><span class="st">&gt;&quot;</span> <span class="op">%</span> (a, a.upper()))</code></pre></div>
<pre><code>大小写判断和转换
All elements in &lt;Sdsdsd&gt; is lowercase: False
Transfer all elments in &lt;Sdsdsd&gt; to lowerse &lt;sdsdsd&gt;
Transfer all elments in &lt;Sdsdsd&gt; to upperse &lt;SDSDSD&gt;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;这个是个保留节目，有兴趣的看，无兴趣的跳过不影响学习&quot;</span>)
<span class="bu">print</span>(<span class="st">&#39;&#39;&#39;字符串是不可修改的，</span>
<span class="st">同一个变量名字赋不同的只实际是产生了多个不同的变量。</span>
<span class="st">不同的变量名字赋同样的值，用于比较时相等，但引用不同的区域&#39;&#39;&#39;</span>)


b <span class="op">=</span> <span class="st">&quot;123456&quot;</span>
<span class="co">## print b</span>
<span class="bu">print</span>(<span class="st">&quot;The memory index of b is&quot;</span>, <span class="bu">id</span>(b))
<span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">1</span>, <span class="dv">15</span>, <span class="dv">2</span>):
    b <span class="op">=</span> b <span class="op">+</span> <span class="st">&#39;123456&#39;</span>
    <span class="co"># print b</span>
    <span class="bu">print</span>(<span class="st">&quot;The memory index of b is&quot;</span>, <span class="bu">id</span>(b))</code></pre></div>
<pre><code>这个是个保留节目，有兴趣的看，无兴趣的跳过不影响学习
字符串是不可修改的，
同一个变量名字赋不同的只实际是产生了多个不同的变量。
不同的变量名字赋同样的值，用于比较时相等，但引用不同的区域
The memory index of b is 139844870936200
The memory index of b is 139844868463728
The memory index of b is 139844870954056
The memory index of b is 139844863857088
The memory index of b is 139844863857088
The memory index of b is 139845221506544
The memory index of b is 139844869671408
The memory index of b is 139844868660840</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;字符串转数组&quot;</span>)
<span class="bu">print</span>()
str1 <span class="op">=</span> <span class="st">&quot;ACTG&quot;</span>
<span class="bu">print</span>(<span class="bu">list</span>(str1))
a <span class="op">=</span> <span class="bu">list</span>(str1)

<span class="bu">print</span>()
<span class="bu">print</span>(<span class="st">&quot;字符串转数组之后就可以逆序了，得到其反向序列&quot;</span>)
<span class="bu">print</span>()
a.reverse()
<span class="bu">print</span>(<span class="st">&#39;&#39;</span>.join(a))</code></pre></div>
<pre><code>字符串转数组

[&#39;A&#39;, &#39;C&#39;, &#39;T&#39;, &#39;G&#39;]

字符串转数组之后就可以逆序了，得到其反向序列

GTCA</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;数字字符串转数值&quot;</span>)
a <span class="op">=</span> <span class="st">&#39;123&#39;</span>
<span class="bu">print</span>(a <span class="op">+</span> <span class="st">&#39;1&#39;</span>, <span class="bu">int</span>(a) <span class="op">+</span> <span class="dv">1</span>)
a <span class="op">=</span> <span class="st">&#39;123.5&#39;</span>

<span class="bu">print</span>()
<span class="co">## print a + 1</span>
<span class="bu">print</span>(<span class="bu">float</span>(a) <span class="op">+</span> <span class="dv">1</span>)
<span class="bu">print</span>(<span class="st">&#39;&#39;&#39;从文件或命令行参数中取出的数字都是字符串形式出现，</span>
<span class="st">做四则运算时要先用int 或 float转换。&#39;&#39;&#39;</span>)</code></pre></div>
<pre><code>数字字符串转数值
1231 124

124.5
从文件或命令行参数中取出的数字都是字符串形式出现，
做四则运算时要先用int 或 float转换。</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;字符串倍增&quot;</span>)
a <span class="op">=</span> <span class="st">&quot;ehbio &quot;</span>
a <span class="op">*</span> <span class="dv">4</span></code></pre></div>
<pre><code>字符串倍增





&#39;ehbio ehbio ehbio ehbio &#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">*</span> <span class="dv">0</span></code></pre></div>
<pre><code>&#39;&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 倍增不可以是小数</span>
a <span class="op">*</span> <span class="fl">3.1</span></code></pre></div>
<pre><code>---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

&lt;ipython-input-21-c65dd4dac397&gt; in &lt;module&gt;()
----&gt; 1 a * 3.1


TypeError: can&#39;t multiply sequence by non-int of type &#39;float&#39;</code></pre>
</div>
<div id="breakcontinue-1" class="section level4">
<h4><span class="header-section-number">2.3.3.7</span> break和continue</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 模拟登陆账号, 用户名 Bob, 密码fish</span>
<span class="cf">while</span> <span class="va">True</span>:
    name <span class="op">=</span> <span class="bu">input</span>(<span class="st">&#39;Who are you?</span><span class="ch">\n</span><span class="st">&gt; &#39;</span>)
    <span class="cf">if</span> name <span class="op">!=</span> <span class="st">&#39;Bob&#39;</span>:
        <span class="cf">continue</span>  <span class="co"># 将程序跳转到开头</span>
    password <span class="op">=</span> <span class="bu">input</span>(<span class="st">&#39;Hello, Bob. What is your password? (password: fish)</span><span class="ch">\n</span><span class="st">&gt; &#39;</span>)
    <span class="cf">if</span> password <span class="op">==</span> <span class="st">&#39;fish&#39;</span>:
        <span class="cf">break</span> <span class="co"># 跳出所在循环或最内层循环</span>
<span class="bu">print</span>(<span class="st">&#39;Acess granted!&#39;</span>)</code></pre></div>
<pre><code>Who are you?
&gt; CT
Who are you?
&gt; Bob
Hello, Bob. What is your password? (password: fish)
&gt; sdsds
Who are you?
&gt; Bob
Hello, Bob. What is your password? (password: fish)
&gt; fish
Acess granted!</code></pre>
</div>
<div id="for-range-" class="section level4">
<h4><span class="header-section-number">2.3.3.8</span> for range (获取一系列数)</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 如果只给一个参数，则是从0-给定参数(不包括)，步长为1</span>
<span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">4</span>):
    <span class="bu">print</span>(i)</code></pre></div>
<pre><code>0
1
2
3</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 1: start; 10: end (不包括); 2: step</span>
<span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">1</span>,<span class="dv">10</span>,<span class="dv">2</span>):
    <span class="bu">print</span>(i)</code></pre></div>
<pre><code>1
3
5
7
9</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 步长也可以为负值，从大到小</span>
<span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">10</span>,<span class="dv">1</span>,<span class="op">-</span><span class="dv">2</span>):
    <span class="bu">print</span>(i)</code></pre></div>
<pre><code>10
8
6
4
2</code></pre>
<p>高斯计算1-100的加和。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 高斯的1+2+3+...+100=?</span>
total <span class="op">=</span> <span class="dv">0</span>

<span class="co">## 参数是101，为什么呢？</span>
<span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">1</span>,<span class="dv">101</span>):
    total <span class="op">=</span> total <span class="op">+</span> i
<span class="bu">print</span>(total)</code></pre></div>
<pre><code>5050</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 高斯优化后的</span>
end <span class="op">=</span> <span class="dv">100</span>
sum_all <span class="op">=</span> <span class="bu">int</span>((<span class="dv">1</span><span class="op">+</span>end) <span class="op">*</span> end <span class="op">/</span> <span class="dv">2</span>)
<span class="co">##else:</span>
<span class="co">##    sum_all = end * (end -1 ) / 2 + end</span>
<span class="bu">print</span>(sum_all)</code></pre></div>
<pre><code>5050</code></pre>
<p>脑筋急转弯，题目如下:</p>
<p>现有100元钱，需要买100个物品，其中铅笔盒单价5元，笔单价3元，橡皮单价0.5元，怎么组合可以把100元花完，同时三种物品的个数和为100，请用编程解决。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 纯暴力解法</span>
<span class="cf">for</span> x <span class="op">in</span> <span class="bu">range</span>(<span class="dv">0</span>, <span class="dv">101</span>):
    <span class="cf">for</span> y <span class="op">in</span> <span class="bu">range</span>(<span class="dv">0</span>, <span class="dv">101</span>):
        <span class="cf">for</span> z <span class="op">in</span> <span class="bu">range</span>(<span class="dv">0</span>, <span class="dv">101</span>):
            <span class="cf">if</span> x <span class="op">+</span> y <span class="op">+</span> z <span class="op">==</span> <span class="dv">100</span> <span class="op">and</span> <span class="dv">5</span> <span class="op">*</span> x <span class="op">+</span> <span class="dv">3</span> <span class="op">*</span> y <span class="op">+</span> <span class="fl">0.5</span> <span class="op">*</span> z <span class="op">==</span> <span class="dv">100</span>:
                <span class="bu">print</span>(x, y, z)</code></pre></div>
<pre><code>0 20 80
5 11 84
10 2 88</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 优化后的暴力解法</span>
<span class="co">## 限定box和pen的最大数目，也就是全部钱只买他们，最多能买多少个？</span>
max_box <span class="op">=</span> <span class="bu">int</span>(<span class="dv">100</span> <span class="op">/</span> <span class="dv">5</span>) <span class="op">+</span> <span class="dv">1</span>
max_pen <span class="op">=</span> <span class="bu">int</span>(<span class="dv">100</span> <span class="op">/</span> <span class="dv">3</span>) <span class="op">+</span> <span class="dv">1</span>
<span class="cf">for</span> box_num <span class="op">in</span> <span class="bu">range</span>(max_box):
    <span class="co"># 需要买的物品总数是固定的，</span>
    <span class="cf">for</span> pen_num <span class="op">in</span> <span class="bu">range</span>(max_pen <span class="op">-</span> box_num):
        eraser_num <span class="op">=</span> <span class="dv">100</span> <span class="op">-</span> box_num <span class="op">-</span> pen_num
        <span class="cf">if</span> <span class="dv">5</span> <span class="op">*</span> box_num <span class="op">+</span> <span class="dv">3</span> <span class="op">*</span> pen_num <span class="op">+</span> <span class="fl">0.5</span> <span class="op">*</span> eraser_num <span class="op">==</span> <span class="dv">100</span>:
            <span class="bu">print</span>((box_num, pen_num, eraser_num))</code></pre></div>
<pre><code>(0, 20, 80)
(5, 11, 84)
(10, 2, 88)</code></pre>
</div>
<div id="section-2.3.3.9" class="section level4">
<h4><span class="header-section-number">2.3.3.9</span> 列表操作</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;#构建一个数组&quot;</span>)
aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]
<span class="bu">print</span>(aList)
<span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">数组可以用下标或区域进行索引</span><span class="ch">\n</span><span class="st">&quot;</span>)
<span class="bu">print</span>(<span class="st">&quot;The first element is </span><span class="sc">%d</span><span class="st">.&quot;</span> <span class="op">%</span> aList[<span class="dv">0</span>])
<span class="bu">print</span>()
<span class="bu">print</span>(<span class="st">&quot;The last element is </span><span class="sc">%d</span><span class="st">.&quot;</span> <span class="op">%</span> aList[<span class="op">-</span><span class="dv">1</span>])
<span class="bu">print</span>()
<span class="bu">print</span>(<span class="st">&quot;The first two elements are&quot;</span>, aList[:<span class="dv">2</span>])
<span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">数组索引和切片操作与字符串是一样一样的，而且都很重要。&quot;</span>)</code></pre></div>
<pre><code>#构建一个数组
[1, 2, 3, 4, 5]

数组可以用下标或区域进行索引

The first element is 1.

The last element is 5.

The first two elements are [1, 2]

数组索引和切片操作与字符串是一样一样的，而且都很重要。</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> []
<span class="bu">print</span>(<span class="st">&quot;#append: 向数组中增加元素&quot;</span>)
aList.append(<span class="dv">6</span>)
<span class="bu">print</span>(aList)

<span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">#extend: 向数组中增加一个数组&quot;</span>)
<span class="bu">print</span>()
bList <span class="op">=</span> [<span class="st">&#39;a&#39;</span>, <span class="st">&#39;b&#39;</span>, <span class="st">&#39;c&#39;</span>]
aList.extend(bList)
<span class="bu">print</span>(aList)

aList <span class="op">+</span> bList</code></pre></div>
<pre><code>#append: 向数组中增加元素
[6]

#extend: 向数组中增加一个数组

[6, &#39;a&#39;, &#39;b&#39;, &#39;c&#39;]





[6, &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;a&#39;, &#39;b&#39;, &#39;c&#39;]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">3</span>, <span class="dv">5</span>]
<span class="bu">print</span>(<span class="st">&quot;在数组中删除元素&quot;</span>)
aList.remove(<span class="dv">3</span>)  <span class="co"># 只删除第一个匹配的 3</span>
<span class="bu">print</span>()
<span class="bu">print</span>(aList)

aList.pop(<span class="dv">3</span>)  <span class="co"># 移除元素的下标为3的字符</span>
<span class="bu">print</span>()
<span class="bu">print</span>(aList)
<span class="bu">print</span>(<span class="st">&#39;&#39;&#39;</span><span class="ch">\n</span><span class="st">pop和remove是不一样的，remove是移除等于给定值的元素，</span>
<span class="st">pop是移除给定位置的元素</span><span class="ch">\n</span><span class="st">&#39;&#39;&#39;</span>)</code></pre></div>
<pre><code>在数组中删除元素

[1, 2, 4, 3, 5]

[1, 2, 4, 5]

pop和remove是不一样的，remove是移除等于给定值的元素，
pop是移除给定位置的元素</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]

<span class="bu">print</span>(<span class="st">&quot;#遍历数组的每个元素&quot;</span>)
<span class="bu">print</span>()
<span class="cf">for</span> ele <span class="op">in</span> aList:
    <span class="bu">print</span>(ele)

<span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">#输出数组，并输出大于3的元素&quot;</span>)
<span class="bu">print</span>()

<span class="cf">for</span> ele <span class="op">in</span> aList:
    <span class="cf">if</span> ele <span class="op">&gt;</span> <span class="dv">3</span>:
        <span class="bu">print</span>(ele)</code></pre></div>
<pre><code>#遍历数组的每个元素

1
2
3
4
5
#输出数组中大于3的元素

4
5</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> [i <span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">30</span>)]
aList
aList <span class="op">=</span> [i <span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">30</span>) <span class="cf">if</span> i <span class="op">%</span> <span class="dv">2</span> <span class="op">==</span><span class="dv">0</span>]
aList</code></pre></div>
<pre><code>[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> [i <span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">30</span>)]
<span class="bu">print</span>(<span class="st">&quot;#输出数组中大于3,且小于10的元素&quot;</span>)
<span class="bu">print</span>()

<span class="cf">for</span> ele <span class="op">in</span> aList:
    <span class="cf">if</span> ele <span class="op">&gt;</span> <span class="dv">3</span> <span class="op">and</span> ele <span class="op">&lt;</span> <span class="dv">10</span>:  <span class="co"># 逻辑与，当两个条件都符合时才输出</span>
        <span class="bu">print</span>(ele)</code></pre></div>
<pre><code>#输出数组中大于3,且小于10的元素

4
5
6
7
8
9</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> [i <span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">30</span>)]
<span class="bu">print</span>(<span class="st">&quot;#输出数组中大于25,或小于5的元素&quot;</span>)
<span class="bu">print</span>()

<span class="cf">for</span> ele <span class="op">in</span> aList:
    <span class="cf">if</span> ele <span class="op">&gt;</span> <span class="dv">25</span> <span class="op">or</span> ele <span class="op">&lt;</span> <span class="dv">5</span>:  <span class="co"># 逻辑或，当两个条件满足一个时就输出</span>
        <span class="bu">print</span>(ele)</code></pre></div>
<pre><code>#输出数组中大于25,或小于5的元素

0
1
2
3
4
26
27
28
29</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> [i <span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">30</span>)]
<span class="bu">print</span>(<span class="st">&quot;#输出数组中不大于3的元素&quot;</span>)
<span class="bu">print</span>()

<span class="cf">for</span> ele <span class="op">in</span> aList:
    <span class="co"># 逻辑非，当不符合给定条件时才输出。</span>
    <span class="co"># 对于这个例子就是ele不大于3时才输出，相当于 if ele &lt;= 3:</span>
    <span class="cf">if</span> <span class="op">not</span> ele <span class="op">&gt;</span> <span class="dv">3</span>:
        <span class="bu">print</span>(ele)</code></pre></div>
<pre><code>#输出数组中大于3,且小于10的元素

0
1
2
3</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]
<span class="bu">print</span>(<span class="st">&#39;</span><span class="ch">\t</span><span class="st">&#39;</span>.join(aList)) <span class="co">#wrong</span></code></pre></div>
<pre><code>---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

&lt;ipython-input-33-193d4492669b&gt; in &lt;module&gt;()
      1 aList = [1, 2, 3, 4, 5]
----&gt; 2 print(&#39;\t&#39;.join(aList)) #wrong


TypeError: sequence item 0: expected str instance, int found</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;连接数组的每个元素（每个元素必须为字符串）&quot;</span>)
aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]
<span class="co">## print &#39;\t&#39;.join(aList) #wrong</span>

<span class="bu">print</span>(aList)
aList <span class="op">=</span> [<span class="bu">str</span>(i) <span class="cf">for</span> i <span class="op">in</span> aList]
<span class="bu">print</span>(aList)
<span class="bu">print</span>(<span class="st">&#39;</span><span class="ch">\t</span><span class="st">&#39;</span>.join(aList))

<span class="bu">print</span>(<span class="st">&#39;:&#39;</span>.join(aList))
<span class="bu">print</span>(<span class="st">&#39;&#39;</span>.join(aList))

<span class="bu">print</span>(<span class="st">&#39;&#39;&#39;</span><span class="ch">\n</span><span class="st">先把字符串存到列表，再使用join连接，</span>
<span class="st">是最合适的连接大量字符串的方式&#39;&#39;&#39;</span>)</code></pre></div>
<pre><code>连接数组的每个元素（每个元素必须为字符串）
[1, 2, 3, 4, 5]
[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;]
1   2   3   4   5
1:2:3:4:5
12345

先把字符串存到列表，再使用join连接，
是最合适的连接大量字符串的方式</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]

<span class="bu">print</span>(<span class="st">&quot;数组反序&quot;</span>)
aList.reverse()
<span class="bu">print</span>(aList)

<span class="bu">print</span>(<span class="st">&quot;数组元素排序&quot;</span>)
aList.sort()
<span class="bu">print</span>(aList)

<span class="co">## print &quot;lambda排序，保留节目&quot;</span>
<span class="co">##aList.sort(key=lambda x: x*(-1))</span>
<span class="co">## print aList</span></code></pre></div>
<pre><code>数组反序
[5, 4, 3, 2, 1]
数组元素排序
[1, 2, 3, 4, 5]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> [[<span class="dv">1</span>,<span class="dv">2</span>], [<span class="dv">3</span>,<span class="dv">4</span>], [<span class="dv">2</span>,<span class="dv">1</span>]]
aList.sort()
aList</code></pre></div>
<pre><code>[[1, 2], [2, 1], [3, 4]]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList.sort(key<span class="op">=</span><span class="kw">lambda</span> x: x[<span class="dv">1</span>])
aList</code></pre></div>
<pre><code>[[2, 1], [1, 2], [3, 4]]</code></pre>
</div>
<div id="section-2.3.3.10" class="section level4">
<h4><span class="header-section-number">2.3.3.10</span> 集合操作</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;构建一个集合&quot;</span>)
aSet <span class="op">=</span> <span class="bu">set</span>([])
aSet <span class="op">=</span> <span class="bu">set</span>([<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>])
<span class="bu">print</span>(aSet)

<span class="bu">print</span>(<span class="st">&quot;增加一个元素&quot;</span>)
aSet.add(<span class="dv">4</span>)
<span class="bu">print</span>(aSet)
aSet.add(<span class="dv">3</span>)
<span class="bu">print</span>(aSet)</code></pre></div>
<pre><code>构建一个集合
{1, 2, 3}
增加一个元素
{1, 2, 3, 4}
{1, 2, 3, 4}</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;采用转换为集合去除列表中的重复元素&quot;</span>)
aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">1</span>, <span class="dv">3</span>, <span class="dv">1</span>, <span class="dv">5</span>, <span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">3</span>, <span class="dv">3</span>, <span class="dv">6</span>]
<span class="bu">print</span>(aList)
<span class="bu">print</span>(<span class="bu">set</span>(aList))
<span class="bu">print</span>(<span class="bu">list</span>(<span class="bu">set</span>(aList)))</code></pre></div>
<pre><code>采用转换为集合去除列表中的重复元素
[1, 2, 1, 3, 1, 5, 2, 4, 3, 3, 6]
{1, 2, 3, 4, 5, 6}
[1, 2, 3, 4, 5, 6]</code></pre>
</div>
<div id="range" class="section level4">
<h4><span class="header-section-number">2.3.3.11</span> Range使用</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">使用range，产生一系列的字符串</span><span class="ch">\n</span><span class="st">&quot;</span>)
<span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">16</span>):
    <span class="cf">if</span> i <span class="op">%</span> <span class="dv">4</span> <span class="op">==</span> <span class="dv">0</span>:
        <span class="bu">print</span>(i)
<span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">通过指定步长产生4的倍数的数</span><span class="ch">\n</span><span class="st">&quot;</span>)
<span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">0</span>, <span class="dv">16</span>, <span class="dv">4</span>):
    <span class="bu">print</span>(i)</code></pre></div>
<pre><code>使用range，产生一系列的字符串

0
4
8
12

通过指定步长产生4的倍数的数

0
4
8
12</code></pre>
</div>
<div id="section-2.3.3.12" class="section level4">
<h4><span class="header-section-number">2.3.3.12</span> 字典操作</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;#构建一个字典&quot;</span>)
aDict <span class="op">=</span> {}
aDict <span class="op">=</span> {<span class="dv">1</span>: <span class="dv">2</span>, <span class="dv">3</span>: <span class="dv">4</span>, <span class="st">&#39;a&#39;</span>: [<span class="st">&#39;b&#39;</span>,<span class="st">&#39;d&#39;</span>], <span class="st">&#39;d&#39;</span>: <span class="st">&#39;c&#39;</span>,
        <span class="co">&#39;e&#39;</span>: {<span class="dv">1</span>:<span class="dv">2</span>}}

<span class="bu">print</span>(<span class="st">&quot;打印字典&quot;</span>)
<span class="bu">print</span>(aDict)

<span class="bu">print</span>(<span class="st">&quot;向字典中添加键值对&quot;</span>)
aDict[<span class="dv">5</span>] <span class="op">=</span> <span class="dv">6</span>
aDict[<span class="st">&#39;e&#39;</span>] <span class="op">=</span> <span class="st">&#39;f&#39;</span>
<span class="bu">print</span>(aDict)</code></pre></div>
<pre><code>#构建一个字典
打印字典
{1: 2, 3: 4, &#39;a&#39;: [&#39;b&#39;, &#39;d&#39;], &#39;d&#39;: &#39;c&#39;, &#39;e&#39;: {1: 2}}
向字典中添加键值对
{1: 2, 3: 4, &#39;a&#39;: [&#39;b&#39;, &#39;d&#39;], &#39;d&#39;: &#39;c&#39;, &#39;e&#39;: &#39;f&#39;, 5: 6}</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>()
aDict <span class="op">=</span> {<span class="dv">1</span>: <span class="dv">2</span>, <span class="dv">3</span>: <span class="dv">4</span>, <span class="st">&#39;a&#39;</span>: <span class="st">&#39;b&#39;</span>, <span class="st">&#39;d&#39;</span>: <span class="st">&#39;c&#39;</span>}
<span class="bu">print</span>(<span class="st">&quot;输出字典的键值对(key-value)&quot;</span>)
<span class="cf">for</span> key, value <span class="op">in</span> <span class="bu">list</span>(aDict.items()):
    <span class="bu">print</span>(key, value)</code></pre></div>
<pre><code>输出字典的键值对(key-value)
1 2
3 4
a b
d c</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;有序输出字典的键值对(key-value)&quot;</span>)
aDict <span class="op">=</span> {<span class="st">&#39;1&#39;</span>: <span class="dv">2</span>, <span class="st">&#39;3&#39;</span>: <span class="dv">4</span>, <span class="st">&#39;a&#39;</span>: <span class="st">&#39;b&#39;</span>, <span class="st">&#39;d&#39;</span>: <span class="st">&#39;c&#39;</span>}
keyL <span class="op">=</span> <span class="bu">list</span>(aDict.keys())
<span class="bu">print</span>(keyL)

<span class="co">## Python3中不支持int型和str型的比较</span>
<span class="co">## 需要先都转换为str型</span>
<span class="co">## keyL = [str(i) for i in keyL]</span>
keyL.sort()
<span class="bu">print</span>(keyL)
<span class="cf">for</span> key <span class="op">in</span> keyL:
    <span class="bu">print</span>(key, aDict[key])</code></pre></div>
<pre><code>有序输出字典的键值对(key-value)
[&#39;1&#39;, &#39;3&#39;, &#39;a&#39;, &#39;d&#39;]
[&#39;1&#39;, &#39;3&#39;, &#39;a&#39;, &#39;d&#39;]
1 2
3 4
a b
d c</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;字典的value可以是一个列表&quot;</span>)
a <span class="op">=</span> <span class="st">&#39;key&#39;</span>
b <span class="op">=</span> <span class="st">&#39;key2&#39;</span>
aDict <span class="op">=</span> {}
<span class="bu">print</span>(aDict)
aDict[a] <span class="op">=</span> []
<span class="bu">print</span>(aDict)
aDict[a].append(<span class="dv">1</span>)
aDict[a].append(<span class="dv">2</span>)
<span class="bu">print</span>(aDict)
aDict[b] <span class="op">=</span> [<span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]

<span class="bu">print</span>()
<span class="cf">for</span> key, subL <span class="op">in</span> <span class="bu">list</span>(aDict.items()):
    <span class="bu">print</span>(key)
    <span class="cf">for</span> item <span class="op">in</span> subL:
        <span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\t</span><span class="sc">%s</span><span class="st">&quot;</span> <span class="op">%</span> item)

<span class="bu">print</span>(<span class="st">&quot;这个在存取读入的文件时会很有用的，下面的实战练习会用到这个。&quot;</span>)</code></pre></div>
<pre><code>字典的value可以是一个列表
{}
{&#39;key&#39;: []}
{&#39;key&#39;: [1, 2]}

key
    1
    2
key2
    3
    4
    5
这个在存取读入的文件时会很有用的，下面的实战练习会用到这个。</code></pre>
<p>字典可以用中文做Key，中文做value。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aDict <span class="op">=</span> {<span class="st">&#39;菜根谭&#39;</span>: <span class="st">&#39;事理因人言而悟者，有悟还有迷，总不如自悟之了了；意兴从外境而得者，有得还有失，总不如自得之休休。&#39;</span>}
<span class="bu">print</span>(aDict[<span class="st">&#39;菜根谭&#39;</span>])</code></pre></div>
<pre><code>事理因人言而悟者，有悟还有迷，总不如自悟之了了；意兴从外境而得者，有得还有失，总不如自得之休休。</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;字典的value也可以是字典&quot;</span>)
a <span class="op">=</span> <span class="st">&#39;key&#39;</span>
b <span class="op">=</span> <span class="st">&#39;key2&#39;</span>
aDict <span class="op">=</span> {}
<span class="bu">print</span>(aDict)
aDict[a] <span class="op">=</span> {}
<span class="bu">print</span>(aDict)
aDict[a][<span class="st">&#39;subkey&#39;</span>] <span class="op">=</span> <span class="st">&#39;subvalue&#39;</span>
<span class="bu">print</span>(aDict)
aDict[b] <span class="op">=</span> {<span class="dv">1</span>: <span class="dv">2</span>, <span class="dv">3</span>: <span class="dv">4</span>}

<span class="co">##aDict[(a,b)] = 2</span>
<span class="co">##aDict[&#39;a&#39;] = 2</span>
<span class="co">##aDict[&#39;b&#39;] = 2</span>

<span class="bu">print</span>()
<span class="cf">for</span> key, subD <span class="op">in</span> <span class="bu">list</span>(aDict.items()):
    <span class="bu">print</span>(key)
    <span class="cf">for</span> subKey, subV <span class="op">in</span> <span class="bu">list</span>(subD.items()):
        <span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\t</span><span class="sc">%s</span><span class="ch">\t</span><span class="sc">%s</span><span class="st">&quot;</span> <span class="op">%</span> (subKey, subV))

<span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">这个在存取读入的文件时会很有用的，下面的实战练习会用到这个。&quot;</span>)</code></pre></div>
<pre><code>字典的value也可以是字典
{}
{&#39;key&#39;: {}}
{&#39;key&#39;: {&#39;subkey&#39;: &#39;subvalue&#39;}}

key
    subkey  subvalue
key2
    1   2
    3   4

这个在存取读入的文件时会很有用的，下面的实战练习会用到这个。</code></pre>
</div>
</div>
</div>
<div id="section-2.4" class="section level2">
<h2><span class="header-section-number">2.4</span> 输入输出</h2>
<div id="section-2.4.1" class="section level3">
<h3><span class="header-section-number">2.4.1</span> 交互式输入输出</h3>
<p>在很多时候，你会想要让你的程序与用户（可能是你自己）交互。你会从用户那里得到输入，然后打印一些结果。我们可以分别使用raw_input和print语句来完成这些功能。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="bu">input</span>(<span class="st">&quot;Please input a string and type enter</span><span class="ch">\n</span><span class="st">&gt; &quot;</span>)

<span class="bu">print</span>(<span class="st">&quot;The string you typed in is: &quot;</span>, a)</code></pre></div>
<pre><code>Please input a string
&gt; sheng xin bao dian
The string you typed in is:  sheng xin bao dian</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;这是一个保留例子，仅供玩耍</span><span class="ch">\n</span><span class="st">&quot;</span>)
lucky_num <span class="op">=</span> <span class="dv">5</span>
c <span class="op">=</span> <span class="dv">0</span>

<span class="cf">while</span> <span class="va">True</span>:
    b <span class="op">=</span> <span class="bu">int</span>(<span class="bu">input</span>(<span class="st">&quot;Please input a number to check if you are \</span>
<span class="st">lucky enough to guess right: </span><span class="ch">\n</span><span class="st">&quot;</span>))
    <span class="cf">if</span> b <span class="op">==</span> lucky_num:
        <span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">Your are so smart!!! ^_^ ^_^&quot;</span>)
        <span class="co">#----------------------------------------------------</span>
    <span class="co">#--------------------------------------------------------</span>
    <span class="cf">else</span>:
        <span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">Sorry, but you are not right. %&gt;_&lt;%&quot;</span>)
        <span class="cf">while</span> <span class="dv">1</span>:
            c <span class="op">=</span> <span class="bu">input</span>(<span class="st">&quot;Do you want to try again? [Y/N] </span><span class="ch">\n</span><span class="st">&quot;</span>)
            <span class="cf">if</span> c <span class="op">==</span> <span class="st">&#39;Y&#39;</span>:
                try_again <span class="op">=</span> <span class="dv">1</span>
                <span class="cf">break</span>
            <span class="cf">elif</span> c <span class="op">==</span> <span class="st">&#39;N&#39;</span>:
                try_again <span class="op">=</span> <span class="dv">0</span>
                <span class="cf">break</span>
            <span class="cf">else</span>:
                <span class="bu">print</span>(<span class="st">&quot;I can not understand you, please check your input. </span><span class="ch">\n</span><span class="st">&quot;</span>)
                <span class="cf">continue</span>
        <span class="co">#----------------------------------------------------</span>
        <span class="cf">if</span> try_again:
            <span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">Here comes another run. Enjoy!</span><span class="ch">\n</span><span class="st">&quot;</span>)
            <span class="cf">continue</span>
        <span class="cf">else</span>:
            <span class="bu">print</span>(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">Bye-bye</span><span class="ch">\n</span><span class="st">&quot;</span>)
            <span class="cf">break</span></code></pre></div>
<pre><code>这是一个保留例子，仅供玩耍

Please input a number to check if you are lucky enough to guess right: 
4

Sorry, but you are not right. %&gt;_&lt;%
Do you want to try again? [Y/N] 
Y

Here comes another run. Enjoy!

Please input a number to check if you are lucky enough to guess right: 
3

Sorry, but you are not right. %&gt;_&lt;%
Do you want to try again? [Y/N] 
N

Bye-bye</code></pre>
</div>
<div id="section-2.4.2" class="section level3">
<h3><span class="header-section-number">2.4.2</span> 文件读写</h3>
<p>文件读写是最常见的输入和输出操作。你可以实用<code>file</code>或<code>open</code>来实现。</p>
<div id="section-2.4.2.1" class="section level4">
<h4><span class="header-section-number">2.4.2.1</span> 文件路径</h4>
<p>读写文件时若没有指定文件路径，默认为当前目录。因此需要知道当前所在的目录，然后判断要读取的文件是否在当前目录。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">import</span> os
os.getcwd()
<span class="co">## os.chdir(&quot;path&quot;)</span></code></pre></div>
<pre><code>&#39;/MPATHB/ct/ipython/notebook&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;新建一个文件&quot;</span>)

context <span class="op">=</span> <span class="st">&#39;&#39;&#39;The best way to learn python contains two steps:</span>
<span class="st">1. Rember basic things mentionded here masterly.</span>

<span class="st">2. Practise with real demands.</span>
<span class="st">&#39;&#39;&#39;</span>

<span class="bu">print</span>(<span class="st">&quot;以写入模式(w)打开一个文件并命名为(Test_file.txt)&quot;</span>)
fh <span class="op">=</span> <span class="bu">open</span>(<span class="st">&quot;Test_file.txt&quot;</span>, <span class="st">&quot;w&quot;</span>)
<span class="bu">print</span>(context, <span class="bu">file</span><span class="op">=</span>fh)
<span class="co">## fh.write(context)</span>
fh.close()  <span class="co"># 文件操作完成后必须关闭文件句柄</span></code></pre></div>
<pre><code>新建一个文件
以写入模式(w)打开一个文件并命名为(Test_file.txt)</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="cf">with</span> <span class="bu">open</span>(<span class="st">&quot;Test_file.txt&quot;</span>, <span class="st">&quot;w&quot;</span>) <span class="im">as</span> fh:
    <span class="bu">print</span>(context, <span class="bu">file</span><span class="op">=</span>fh)</code></pre></div>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;以只读模式(r)读入一个名为(Test_file.txt)的文件&quot;</span>)

<span class="bu">print</span>()

<span class="cf">for</span> line <span class="op">in</span> <span class="bu">open</span>(<span class="st">&quot;Test_file.txt&quot;</span>):
    <span class="bu">print</span>(line)</code></pre></div>
<pre><code>以只读模式(r)读入一个名为(Test_file.txt)的文件

The best way to learn python contains two steps:

1. Rember basic things mentionded here masterly.



2. Practise with real demands.</code></pre>
<p>仔细看看上面的输出结果，看上去很空，空行比较多。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&#39;&#39;&#39;避免中间空行的输出。</span>
<span class="st">从文件中读取的每一行都带有一个换行符，</span>
<span class="st">而Python的print默认会在输出结束时加上换行符，</span>
<span class="st">因此打印一行会空出一行。为了解决这个问题，有下面两套方案。&#39;&#39;&#39;</span>)

<span class="bu">print</span>(<span class="st">&quot;end=&#39;&#39;&quot;</span>)
<span class="bu">print</span>()

<span class="cf">for</span> line <span class="op">in</span> <span class="bu">open</span>(<span class="st">&quot;Test_file.txt&quot;</span>):
    <span class="bu">print</span>(line, end<span class="op">=</span><span class="st">&#39;&#39;</span>)

<span class="bu">print</span>()

<span class="bu">print</span>(<span class="st">&quot;去掉每行自身的换行符&quot;</span>)
<span class="cf">for</span> line <span class="op">in</span> <span class="bu">open</span>(<span class="st">&quot;Test_file.txt&quot;</span>):
    <span class="bu">print</span>(line.strip())</code></pre></div>
<pre><code>避免中间空行的输出。
从文件中读取的每一行都带有一个换行符，
而Python的print默认会在输出结束时加上换行符，
因此打印一行会空出一行。为了解决这个问题，有下面两套方案。
end=&#39;&#39;

The best way to learn python contains two steps:
1. Rember basic things mentionded here masterly.

2. Practise with real demands.


去掉每行自身的换行符
The best way to learn python contains two steps:
1. Rember basic things mentionded here masterly.

2. Practise with real demands.</code></pre>
</div>
</div>
</div>
<div id="section-2.5" class="section level2">
<h2><span class="header-section-number">2.5</span> 实战练习（一）</h2>
<div id="section-2.5.1" class="section level3">
<h3><span class="header-section-number">2.5.1</span> 背景知识</h3>
<p><strong>1. FASTA文件格式</strong></p>
<blockquote>
<p>&gt;seq_name_1</p>
</blockquote>
<blockquote>
<p>sequence1</p>
</blockquote>
<blockquote>
<p>&gt;seq_name_2</p>
</blockquote>
<blockquote>
<p>sequence2</p>
</blockquote>
<p><strong>2. FASTQ文件格式</strong></p>
<blockquote>
<p><span class="citation">@HWI-ST1223:80:D1FMTACXX:2:1101:1243:2213</span> 1:N:0:AGTCAA</p>
</blockquote>
<blockquote>
<p>TCTGTGTAGCCNTGGCTGTCCTGGAACTCACTTTGTAGACCAGGCTGGCATGCA</p>
</blockquote>
<blockquote>
<ul>
<li></li>
</ul>
</blockquote>
<blockquote>
<p>BCCFFFFFFHH#4AFHIJJJJJJJJJJJJJJJJJIJIJJJJJGHIJJJJJJJJJ</p>
</blockquote>
</div>
<div id="-" class="section level3">
<h3><span class="header-section-number">2.5.2</span> 作业 (一)</h3>
<ol style="list-style-type: decimal">
<li>给定FASTA格式的文件(test1.fa 和 test2.fa)，写一个程序 <code>cat.py</code> 读入文件，并输出到屏幕
<ul>
<li>用到的知识点
<ul>
<li>open(file)</li>
<li>for .. in loop</li>
<li>print</li>
<li>the amazng , or strip() function</li>
</ul></li>
</ul></li>
<li>给定FASTQ格式的文件(test1.fq), 写一个程序 <code>cat.py</code> 读入文件，并输出到屏幕
<ul>
<li>用到的知识点
<ul>
<li>同上</li>
</ul></li>
</ul></li>
<li>写程序 <code>splitName.py</code>, 读入test2.fa, 并取原始序列名字第一个空格前的名字为处理后的序列名字，输出到屏幕
<ul>
<li>用到的知识点
<ul>
<li>split</li>
<li>字符串的索引</li>
</ul></li>
<li><p>输出格式为：</p>
<pre><code>&gt;NM_001011874
gcggcggcgggcgagcgggcgctggagtaggagctg.......</code></pre></li>
</ul></li>
<li>写程序 <code>formatFasta.py</code>, 读入test2.fa，把每条FASTA序列连成一行然后输出
<ul>
<li>用到的知识点
<ul>
<li>join</li>
<li>strip<br />
</li>
</ul></li>
<li><p>输出格式为:</p>
<pre><code>&gt;NM_001011874
gcggcggcgggc......TCCGCTG......GCGTTCACC......CGGGGTCCGGAG</code></pre></li>
</ul></li>
<li>写程序 <code>formatFasta-2.py</code>, 读入test2.fa，把每条FASTA序列分割成80个字母一行的序列
<ul>
<li>用到的知识点
<ul>
<li>字符串切片操作</li>
<li>range</li>
</ul></li>
<li><p>输出格式为</p>
<pre><code>&gt;NM_001011874
gcggcggcgc.(60个字母).TCCGCTGACG #(每行80个字母)
acgtgctacg.(60个字母).GCGTTCACCC
ACGTACGATG(最后一行可不足80个字母)</code></pre></li>
</ul></li>
<li>写程序 <code>sortFasta.py</code>, 读入test2.fa, 并取原始序列名字第一个空格前的名字为处理后的序列名字，排序后输出
<ul>
<li>用到的知识点
<ul>
<li>sort</li>
<li>dict</li>
<li>aDict[key] = []</li>
<li>aDict[key].append(value)</li>
</ul></li>
</ul></li>
<li>提取给定名字的序列
<ul>
<li>写程序 <code>grepFasta.py</code>, 提取fasta.name中名字对应的test2.fa的序列，并输出到屏幕。</li>
<li>写程序 <code>grepFastq.py</code>, 提取fastq.name中名字对应的test1.fq的序列，并输出到文件。
<ul>
<li>用到的知识点
<ul>
<li>print &gt;&gt;fh, or fh.write()</li>
<li>取模运算，4 % 2 == 0</li>
</ul></li>
</ul></li>
</ul></li>
<li>写程序 <code>screenResult.py</code>, 筛选test.expr中foldChange大于2的基因并且padj小于0.05的基，可以输出整行或只输出基因名字
<ul>
<li>用到的知识点
<ul>
<li>逻辑与操作符 and</li>
<li>文件中读取的内容都为字符串，需要用int转换为整数，float转换为浮点数</li>
</ul></li>
</ul></li>
<li>写程序 <code>transferMultipleColumToMatrix.py</code> 将文件(multipleColExpr.txt)中基因在多个组织中的表达数据转换为矩阵形式
<ul>
<li>用到的知识点
<ul>
<li>aDict[‘key’] = {}</li>
<li>aDict[‘key’][‘key2’] = value</li>
<li>if key not in aDict</li>
<li>aDict = {‘ENSG00000000003’: {“A-431”: 21.3, “A-549”, 32.5,…},“ENSG00000000003”:{},}</li>
</ul></li>
<li><p>输入格式(只需要前3列就可以)</p>
<pre><code>Gene    Sample  Value   Unit    Abundance
ENSG00000000003 A-431   21.3    FPKM    Medium
ENSG00000000003 A-549   32.5    FPKM    Medium
ENSG00000000003 AN3-CA  38.2    FPKM    Medium
ENSG00000000003 BEWO    31.4    FPKM    Medium
ENSG00000000003 CACO-2  63.9    FPKM    High
ENSG00000000005 A-431   0.0     FPKM    Not detected
ENSG00000000005 A-549   0.0     FPKM    Not detected
ENSG00000000005 AN3-CA  0.0     FPKM    Not detected
ENSG00000000005 BEWO    0.0     FPKM    Not detected
ENSG00000000005 CACO-2  0.0     FPKM    Not detected</code></pre></li>
<li><p>输出格式</p>
<pre><code>Name    A-431   A-549   AN3-CA  BEWO    CACO-2
ENSG00000000460 25.2    14.2    10.6    24.4    14.2
ENSG00000000938 0.0 0.0 0.0 0.0 0.0
ENSG00000001084 19.1    155.1   24.4    12.6    23.5
ENSG00000000457 2.8 3.4 3.8 5.8 2.9</code></pre></li>
</ul></li>
<li>写程序 <code>reverseComplementary.py</code>计算序列 <code>ACGTACGTACGTCACGTCAGCTAGAC</code>的反向互补序列
<ul>
<li>用到的知识点
<ul>
<li>reverse</li>
<li>list(seq)</li>
</ul></li>
</ul></li>
<li>写程序 <code>collapsemiRNAreads.py</code>转换smRNA-Seq的测序数据
<ul>
<li><p>输入文件格式(mir.collapse, tab-分割的两列文件，第一列为序列，第二列为序列被测到的次数)</p>
<pre><code>ID_REF        VALUE
ACTGCCCTAAGTGCTCCTTCTGGC        2
ATAAGGTGCATCTAGTGCAGATA        25
TGAGGTAGTAGTTTGTGCTGTTT        100
TCCTACGAGTTGCATGGATTC        4</code></pre></li>
<li><p>输出文件格式 (mir.collapse.fa, 名字的前3个字母为样品的特异标示，中间的数字表示第几条序列，是序列名字的唯一标示，第三部分是x加每个reads被测到的次数。三部分用下划线连起来作为fasta序列的名字。)</p>
<pre><code>&gt;ESB_1_x2
ACTGCCCTAAGTGCTCCTTCTGGC
&gt;ESB_2_x25
ATAAGGTGCATCTAGTGCAGATA
&gt;ESB_3_x100
TGAGGTAGTAGTTTGTGCTGTTT
&gt;ESB_4_x4
TCCTACGAGTTGCATGGATTC</code></pre></li>
</ul></li>
<li>简化的短序列匹配程序 (map.py) 把short.fa中的序列比对到ref.fa, 输出短序列匹配到ref.fa文件中哪些序列的哪些位置
<ul>
<li>用到的知识点
<ul>
<li>find</li>
</ul></li>
<li>输出格式 (输出格式为bed格式，第一列为匹配到的染色体，第二列和第三列为匹配到染色体序列的起始终止位置（位置标记以0为起始，代表第一个位置；终止位置不包含在内，第一个例子中所示序列的位置是(199,208](前闭后开，实际是chr1染色体第199-206的序列，0起始). 第4列为短序列自身的序列.)。</li>
<li><p>附加要求：可以只匹配到给定的模板链，也可以考虑匹配到模板链的互补链。这时第5列可以为短序列的名字，第六列为链的信息，匹配到模板链为’+‘，匹配到互补链为’-’。注意匹配到互补链时起始位置也是从模板链的5’端算起的。</p>
<pre><code>chr1    199 208 TGGCGTTCA
chr1    207 216 ACCCCGCTG
chr2    63  70  AAATTGC
chr3    0   7   AATAAAT</code></pre></li>
</ul></li>
<li>备注：
<ul>
<li>每个提到提到的“用到的知识点”为相对于前面的题目新增的知识点，请综合考虑。此外，对于不同的思路并不是所有提到的知识点都会用着，而且也可能会用到未提到的知识点。但是所有知识点都在前面的讲义部分有介绍。</li>
<li>每个程序对于你身边会写的人来说都很简单，因此你一定要克制住，独立去把答案做出，多看错误提示，多比对程序输出结果和预期结果的差异。</li>
<li>学习锻炼“读程序”，即对着文件模拟整个的读入、处理过程来发现可能的逻辑问题。</li>
<li>程序运行没有错误不代表你写的程序完成了你的需求，你要去查验输出结果是不是你想要的。</li>
</ul></li>
<li>关于程序调试
<ul>
<li>在初写程序时，可能会出现各种各样的错误，常见的有缩进不一致，变量名字拼写错误，丢失冒号，文件名未加引号等，这时要根据错误提示查看错误类型是什么，出错的是哪一行来定位错误。当然，有的时候报错的行自身不一定有错，可能是其前面或后面的行出现了错误。</li>
<li><strong>用脑袋运行程序</strong>：当程序写作完成后，自己尝试对着数据文件，一行一行的执行程序，来看程序的运行是否与自己想干的活一致，有没有纰漏。</li>
<li>当结果不符合预期时，要学会<strong>使用print来查看每步的操作是否正确</strong>，比如我读入了字典，我就打印下字典，看看读入的是不是我想要的，是否含有不该存在的字符；或者<strong>在每个判断句、函数调入的情况下打印个字符，来跟踪程序的运行轨迹</strong>。</li>
</ul></li>
</ol>
</div>
</div>
<div id="section-2.6" class="section level2">
<h2><span class="header-section-number">2.6</span> 函数操作</h2>
<p>函数是重用的程序段。它们允许你给一块语句一个名称，然后你可以在你的程序的任何地方使用这个名称任意多次地运行这个语句块。这被称为 <code>调用</code> 函数。我们已经使用了许多内建的函数，比如<code>len</code>, <code>range</code>, <code>input</code>, <code>int</code>, <code>str</code>。</p>
<p>也可以导入特定包里面的函数，比如<code>os.getcwd</code>, <code>sys.exit</code>。</p>
<p>函数通过<code>def</code>关键字定义。<code>def</code>关键字后跟一个函数的 <code>标识符</code> 名称，然后跟一对圆括号。圆括号之中可以包括一些变量名，该行以冒号结尾。接下来是一块语句，它们是函数体。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">##自定义函数</span>
<span class="kw">def</span> print_hello():
    <span class="bu">print</span>(<span class="st">&quot;Hello, you!&quot;</span>)


print_hello()</code></pre></div>
<pre><code>Hello, you!</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> hello(who):
    <span class="bu">print</span>(<span class="st">&quot;Hello, </span><span class="sc">%s</span><span class="st">!&quot;</span> <span class="op">%</span> who)


hello(<span class="st">&#39;you&#39;</span>)
hello(<span class="st">&#39;me&#39;</span>)</code></pre></div>
<pre><code>Hello, you!
Hello, me!</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">##自定义函数</span>

<span class="kw">def</span> sum_num(a, b):
    c <span class="op">=</span> a <span class="op">+</span> b
    <span class="cf">return</span> c

d <span class="op">=</span> sum_num(<span class="dv">3</span>, <span class="dv">4</span>)
d</code></pre></div>
<pre><code>7</code></pre>
<p><strong>局部变量和全局变量</strong></p>
<p>全局作用：函数之外，从定义位置起，所有逻辑下游的语句都可以使用</p>
<p>局部作用：函数之内，出了函数就不可以被识别</p>
<p>局部可以使用<code>global</code>访问全局变量，而全局不能使用局部变量。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">var <span class="op">=</span> <span class="dv">1</span>

<span class="kw">def</span> variable_test():
    var <span class="op">=</span> <span class="dv">2</span>
    <span class="bu">print</span>(<span class="st">&quot;var in variable_test is&quot;</span>,var)

<span class="bu">print</span>(<span class="st">&quot;var before running variable_test()&quot;</span>, var)
variable_test()
<span class="bu">print</span>(<span class="st">&quot;var after running variable_test()&quot;</span>, var)</code></pre></div>
<pre><code>var before running variable_test() 1
var in variable_test is 2
var after running variable_test() 1</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">var <span class="op">=</span> <span class="dv">1</span>

<span class="kw">def</span> variable_test():
    <span class="kw">global</span> var
    var <span class="op">=</span> <span class="dv">2</span>

<span class="bu">print</span>(<span class="st">&quot;var before running variable_test()&quot;</span>, var)
variable_test()
<span class="bu">print</span>(<span class="st">&quot;var after running variable_test()&quot;</span>, var)</code></pre></div>
<pre><code>var before running variable_test() 1
var after running variable_test() 2</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 全局变量在局部作用域中使用</span>
<span class="kw">def</span> spam():
    <span class="bu">print</span>(<span class="st">&quot;eggs in spam&quot;</span>,eggs)

eggs <span class="op">=</span> <span class="dv">28</span>
spam()</code></pre></div>
<pre><code>eggs in spam 28</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 全局变量在局部作用域中使用</span>
<span class="co">## 但若局部也有其定义，容易引发未定义冲突</span>
<span class="kw">def</span> spam():
    <span class="bu">print</span>(eggs)
    eggs <span class="op">=</span> <span class="dv">29</span>


eggs <span class="op">=</span> <span class="dv">28</span>
spam()
<span class="bu">print</span>(eggs)</code></pre></div>
<pre><code>---------------------------------------------------------------------------

UnboundLocalError                         Traceback (most recent call last)

&lt;ipython-input-22-61f9fdfeb6fe&gt; in &lt;module&gt;()
      6 
      7 eggs = 28
----&gt; 8 spam()
      9 print(eggs)


&lt;ipython-input-22-61f9fdfeb6fe&gt; in spam()
      1 # 全局变量在局部作用域中使用
      2 def spam():
----&gt; 3     print(eggs)
      4     eggs = 29
      5 


UnboundLocalError: local variable &#39;eggs&#39; referenced before assignment</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 尽量避免名称相同的局部变量和全局变量</span>
<span class="kw">def</span> spam():
    eggs <span class="op">=</span> <span class="st">&#39;spam local&#39;</span>
    <span class="bu">print</span>(<span class="st">&quot;eggs in spam&quot;</span>,eggs)  <span class="co"># 输出spam local</span>


<span class="kw">def</span> bacon():
    eggs <span class="op">=</span> <span class="st">&#39;bacon local&#39;</span>
    <span class="bu">print</span>(<span class="st">&quot;eggs in bacon&quot;</span>, eggs)  <span class="co"># 输出bacon local</span>
    spam()
    <span class="bu">print</span>(<span class="st">&quot;eggs in bacon after running spam&quot;</span>, eggs)  <span class="co"># 输出bacon local</span>


eggs <span class="op">=</span> <span class="st">&#39;global&#39;</span>
bacon()
<span class="bu">print</span>(<span class="st">&quot;Global eggs&quot;</span>, eggs)</code></pre></div>
<pre><code>eggs in bacon bacon local
eggs in spam spam local
eggs in bacon after running spam bacon local
Global eggs global</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;把之前写过的语句块稍微包装下就是函数了</span><span class="ch">\n</span><span class="st">&quot;</span>)


<span class="kw">def</span> findAll(string, pattern):
    posL <span class="op">=</span> []
    pos <span class="op">=</span> <span class="dv">0</span>
    <span class="cf">for</span> i <span class="op">in</span> string:
        pos <span class="op">+=</span> <span class="dv">1</span>
        <span class="cf">if</span> i <span class="op">==</span> pattern:
            posL.append(pos)
    <span class="co">#-------------------</span>
    <span class="cf">return</span> posL


<span class="co">##------END of findAll-------</span>
a <span class="op">=</span> findAll(<span class="st">&quot;ABCDEFDEACFBACACA&quot;</span>, <span class="st">&quot;A&quot;</span>)
<span class="bu">print</span>(a)
<span class="bu">print</span>(findAll(<span class="st">&quot;ABCDEFDEACFBACACA&quot;</span>, <span class="st">&quot;B&quot;</span>))</code></pre></div>
<pre><code>把之前写过的语句块稍微包装下就是函数了

[1, 9, 13, 15, 17]
[2, 12]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> readFasta(<span class="bu">file</span>):
    aDict <span class="op">=</span> {}
    <span class="cf">for</span> line <span class="op">in</span> <span class="bu">open</span>(<span class="bu">file</span>):
        <span class="cf">if</span> line[<span class="dv">0</span>] <span class="op">==</span> <span class="st">&#39;&gt;&#39;</span>:
            name <span class="op">=</span> line.strip()
            aDict[name] <span class="op">=</span> []
        <span class="cf">else</span>:
            aDict[name].append(line.strip())
    <span class="co">#----------------------------------</span>
    <span class="cf">for</span> name, lineL <span class="op">in</span> <span class="bu">list</span>(aDict.items()):
        aDict[name] <span class="op">=</span> <span class="st">&#39;&#39;</span>.join(lineL)
    <span class="cf">return</span> aDict


<span class="bu">print</span>(readFasta(<span class="st">&quot;data/test1.fa&quot;</span>))
seqD <span class="op">=</span> readFasta(<span class="st">&quot;data/test2.fa&quot;</span>)</code></pre></div>
<pre><code>{&#39;&gt;NM_001011874 gene=Xkr4 CDS=151-2091&#39;: &#39;gcggcggcgggcgagcgggcgctggagtaggagctggggagcggcgcggccggggaaggaagccagggcg&#39;, &#39;&gt;NM_001195662 gene=Rp1 CDS=55-909&#39;: &#39;AGGTCTCACCCAAAATGAGTGACACACCTTCTACTAGTTTCTCCATGATTCATCTGACTTCTGAAGGTCA&#39;, &#39;&gt;NM_0112835 gene=Rp15 CDS=128-6412&#39;: &#39;AATAAATCCAAAGACATTTGTTTACGTGAAACAAGCAGGTTGCATATCCAGTGACGTTTATACAGACCAC&#39;, &#39;&gt;NM_011283 gene=Rp1 CDS=128-6412&#39;: &#39;AATAAATCCAAAGACATTTGTTTACGTGAAACAAGCAGGTTGCATATCCAGTGACGTTTATACAGACCAC&#39;}





{&#39;&gt;NM_001011874 gene=Xkr4 CDS=151-2091&#39;: &#39;gcggcggcgggcgagcgggcgctggagtaggagctggggagcggcgcggccggggaaggaagccagggcgaggcgaggaggtggcgggaggaggagacagcagggacaggTGTCAGATAAAGGAGTGCTCTCCTCCGCTGCCGAGGCATCATGGCCGCTAAGTCAGACGGGAGGCTGAAGATGAAGAAGAGCAGCGACGTGGCGTTCACCCCGCTGCAGAACTCGGACAATTCGGGCTCTGTGCAAGGACTGGCTCCAGGCTTGCCGTCGGGGTCCGGAG&#39;,
 &#39;&gt;NM_001195662 gene=Rp1 CDS=55-909&#39;: &#39;AAGCTCAGCCTTTGCTCAGATTCTCCTCTTGATGAAACAAAGGGATTTCTGCACATGCTTGAGAAATTGCAGGTCTCACCCAAAATGAGTGACACACCTTCTACTAGTTTCTCCATGATTCATCTGACTTCTGAAGGTCAAGTTCCTTCCCCTCGCCATTCAAATATCACTCATCCTGTAGTGGCTAAACGCATCAGTTTCTATAAGAGTGGAGACCCACAGTTTGGCGGCGTTCGGGTGGTGGTCAACCCTCGTTCCTTTAAGACTTTTGACGCTCTGCTGGACAGTTTATCCAGGAAGGTACCCCTGCCCTTTGGGGTAAGGAACATCAGCACGCCCCGTGGACGACACAGCATCACCAGGCTGGAGGAGCTAGAGGACGGCAAGTCTTATGTGTGCTCCCACAATAAGAAGGTGCTG&#39;,
 &#39;&gt;NM_011283 gene=Rp1 CDS=128-6412&#39;: &#39;AATAAATCCAAAGACATTTGTTTACGTGAAACAAGCAGGTTGCATATCCAGTGACGTTTATACAGACCACACAAACTATTTACTCTTTTCTTCGTAAGGAAAGGTTCAACTTCTGGTCTCACCCAAAATGAGTGACACACCTTCTACTAGTTTCTCCATGATTCATCTGACTTCTGAAGGTCAAGTTCCTTCCCCTCGCCATTCAAATATCACTCATCCTGTAGTGGCTAAACGCATCAGTTTCTATAAGAGTGGAGACCCACAGTTTGGCGGCGTTCGGGTGGTGGTCAACCCTCGTTCCTTTAAGACTTTTGACGCTCTGCTGGACAGTTTATCCAGGAAGGTACCCCTGCCCTTTGGGGTAAGGAACATCAGCACGCCCCGTGGACGACACAGCATCACCAGGCTGGAGGAGCTAGAGGACGGCAAGTCTTATGTGTGCTCCCACAATAAGAAGGTGCTGCCAGTTGACCTGGACAAGGCCCGCAGGCGCCCTCGGCCCTGGCTGAGTAGTCGCTCCATAAGCACGCATGTGCAGCTCTGTCCTGCAACTGCCAATATGTCCACCATGGCACCTGGCATGCTCCGTGCCCCAAGGAGGCTCGTGGTCTTCCGGAATGGTGACCCGAA&#39;,
 &#39;&gt;NM_0112835 gene=Rp1 CDS=128-6412&#39;: &#39;AATAAATCCAAAGACATTTGTTTACGTGAAACAAGCAGGTTGCATATCCAGTGACGTTTATACAGACCACACAAACTATTTACTCTTTTCTTCGTAAGGAAAGGTTCAACTTCTGGTCTCACCCAAAATGAGTGACACACCTTCTACTAGTTTCTCCATGATTCATCTGACTTCTGAAGGTCAAGTTCCTTCCCCTCGCCATTCAAATATCACTCATCCTGTAGTGGCTAAACGCATCAGTTTCTATAAGAGTGGAGACCCACAGTTTGGCGGCGTTCGGGTGGTGGTCAACCCTCGTTCCTTTAAGACTTTTGACGCTCTGCTGGACAGTTTATCCAGGAAGGTACCCCTGCCCTTTGGGGTAAGGAACATCAGCACGCCCCGTGGACGACACAGCATCACCAGGCTGGAGGAGCTAGAGGACGGCAAGTCTTATGTGTGCTCCCACAATAAGAAGGTGCTGCCAGTTGACCTGGACAAGGCCCGCAGGCGCCCTCGGCCCTGGCTGAGTAGTCGCTCCATAAGCACGCATGTGCAGCTCTGTCCTGCAACTGCCAATATGTCCACCATGGCACCTGGCATGCTCCGTGCCCCAAGGAGGCTCGTGGTCTTCCGGAATGGTGACCCGAA&#39;}</code></pre>
<div id="section-2.6.1" class="section level3">
<h3><span class="header-section-number">2.6.1</span> 作业（二）</h3>
<ol start="6" style="list-style-type: decimal">
<li>将 “作业（一）” 中的程序块用函数的方式重写，并调用执行
<ul>
<li>用到的知识点
<ul>
<li>def func(para1,para2,…):</li>
<li>func(para1,para2,…)</li>
</ul></li>
</ul></li>
<li>备注：
<ul>
<li>每个提到提到的“用到的知识点”为相对于前面的题目新增的知识点，请综合考虑。此外，对于不同的思路并不是所有提到的知识点都会用着，而且也可能会用到未提到的知识点。但是所有知识点都在前面的讲义部分有介绍。</li>
<li>每个程序对于你身边会写的人来说都很简单，因此你一定要克制住，独立去把答案做出，多看错误提示，多比对程序输出结果和预期结果的差异。</li>
<li>学习锻炼“读程序”，即对着文件模拟整个的读入、处理过程来发现可能的逻辑问题。</li>
<li>程序运行没有错误不代表你写的程序完成了你的需求，你要去插眼输出结果是不是你想要的。</li>
</ul></li>
<li>关于程序调试
<ul>
<li>在初写程序时，可能会出现各种各样的错误，常见的有缩进不一致，变量名字拼写错误，丢失冒号，文件名未加引号等，这时要根据错误提示查看错误类型是什么，出错的是哪一行来定位错误。当然，有的时候报错的行自身不一定有错，可能是其前面或后面的行出现了错误。</li>
<li>当结果不符合预期时，要学会使用print来查看每步的操作是否正确，比如我读入了字典，我就打印下字典，看看读入的是不是我想要的，是否含有不该存在的字符；或者在每个判断句、函数调入的情况下打印个字符，来跟踪程序的运行轨迹。</li>
</ul></li>
</ol>
</div>
</div>
<div id="section-2.7" class="section level2">
<h2><span class="header-section-number">2.7</span> 模块</h2>
<p>Python内置了很多标准库，如做数学运算的 <code>math</code>, 调用系统功能的 <code>sys</code>, 处理正则表达式的 <code>re</code>, 操作系统相关功能的 <code>os</code>等。我们主要关注两个库: * sys * sys.argv 处理命令行参数 * sys.exit() 退出函数 * sys.stdin 标准输入 * sys.stderr 标准错误 * os * os.system()或os.popen() 执行系统命令 * os.getcwd() 获取当前目录 * os.remove() 删除文件</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">import</span> os
os.getcwd()
<span class="co">##help(os.getcwd)</span>
<span class="co">##os.remove(r&#39;D:\project\github\PBR_training\script\splitName.py&#39;)</span>
<span class="co">##os.system(&#39;rm file&#39;)</span></code></pre></div>
<pre><code>&#39;/MPATHB/ct/ipython/notebook&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">from</span> os <span class="im">import</span> getcwd
getcwd()</code></pre></div>
<pre><code>&#39;/MPATHB/ct/ipython/notebook&#39;</code></pre>
</div>
<div id="section-2.8" class="section level2">
<h2><span class="header-section-number">2.8</span> 命令行参数</h2>
<p><code>sys.argv</code>是一个列表，存储了包含程序名字在内的传给程序的命令行参数。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">%%</span>writefile testSys.py
<span class="im">import</span> sys
<span class="bu">print</span>(sys.argv)</code></pre></div>
<pre><code>Writing testSys.py</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">%</span>run testSys <span class="st">&#39;abc&#39;</span> <span class="dv">1</span></code></pre></div>
<pre><code>[&#39;testSys.py&#39;, &#39;abc&#39;, &#39;1&#39;]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">%%</span>writefile cat.py
<span class="im">import</span> sys

<span class="kw">def</span> read_print_file(filename):
    <span class="cf">for</span> line <span class="op">in</span> <span class="bu">open</span>(filename):
        <span class="bu">print</span>(line, end<span class="op">=</span><span class="st">&quot;&quot;</span>)
<span class="co">##------END read_print_file--------------------------</span>

<span class="co">##main函数及其调用部分是我个人写程序的固定格式，照搬就可以</span>
<span class="kw">def</span> main(): <span class="co">#一般主程序会包含在main函数中，在文件的最后调用main函数即可运行程序</span>
    <span class="cf">if</span> <span class="bu">len</span>(sys.argv) <span class="op">&lt;</span> <span class="dv">2</span>:  <span class="co">#如果命令行参数不足两个，则提示操作</span>
        <span class="co">#一般提示信息输出到标准错误</span>
        <span class="bu">print</span>(<span class="st">&quot;Usage: python </span><span class="sc">%s</span><span class="st"> filename&quot;</span> <span class="op">%</span> sys.argv[<span class="dv">0</span>], <span class="bu">file</span><span class="op">=</span>sys.stderr)
        sys.exit(<span class="dv">0</span>)
    <span class="bu">file</span> <span class="op">=</span> sys.argv[<span class="dv">1</span>]
    read_print_file(<span class="bu">file</span>)
<span class="co">##--------END main------------------</span>
<span class="co">##这句话是说只有在文件被执行时才调用main函数。如果这个文件被其它文件调用，则不执行main函数。</span>
<span class="cf">if</span> <span class="va">__name__</span> <span class="op">==</span> <span class="st">&#39;__main__&#39;</span>: 
    main()</code></pre></div>
<pre><code>Writing cat.py</code></pre>
<p>关于<code>__main__</code>的解释见<a href="http://mp.weixin.qq.com/s/JHDvdqq3Z-7uDmsyroblNQ">关于Python中的__main__和编程模板</a>。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">%</span>run cat</code></pre></div>
<pre><code>Usage: python cat.py filename</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">%</span>run cat data<span class="op">/</span>test1.fa</code></pre></div>
<pre><code>&gt;NM_001011874 gene=Xkr4 CDS=151-2091
gcggcggcgggcgagcgggcgctggagtaggagctggggagcggcgcggccggggaaggaagccagggcg
&gt;NM_001195662 gene=Rp1 CDS=55-909
AGGTCTCACCCAAAATGAGTGACACACCTTCTACTAGTTTCTCCATGATTCATCTGACTTCTGAAGGTCA
&gt;NM_0112835 gene=Rp15 CDS=128-6412
AATAAATCCAAAGACATTTGTTTACGTGAAACAAGCAGGTTGCATATCCAGTGACGTTTATACAGACCAC
&gt;NM_011283 gene=Rp1 CDS=128-6412
AATAAATCCAAAGACATTTGTTTACGTGAAACAAGCAGGTTGCATATCCAGTGACGTTTATACAGACCAC</code></pre>
<p>使用 <code>optparse</code>，功能更强大 (保留内容)</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">%%</span>writefile skeleton.py
<span class="co">##!/usr/bin/env python</span>

desc <span class="op">=</span> <span class="st">&#39;&#39;&#39;</span>
<span class="st">Functional description:</span>

<span class="st">&#39;&#39;&#39;</span>

<span class="im">import</span> sys
<span class="im">import</span> os
<span class="im">from</span> time <span class="im">import</span> localtime, strftime 
timeformat <span class="op">=</span> <span class="st">&quot;%Y-%m-</span><span class="sc">%d</span><span class="st"> %H:%M:%S&quot;</span>
<span class="im">from</span> optparse <span class="im">import</span> OptionParser <span class="im">as</span> OP

<span class="kw">def</span> cmdparameter(argv):
    <span class="cf">if</span> <span class="bu">len</span>(argv) <span class="op">==</span> <span class="dv">1</span>:
        <span class="kw">global</span> desc
        <span class="bu">print</span> <span class="op">&gt;&gt;</span>sys.stderr, desc
        cmd <span class="op">=</span> <span class="st">&#39;python &#39;</span> <span class="op">+</span> argv[<span class="dv">0</span>] <span class="op">+</span> <span class="st">&#39; -h&#39;</span>
        os.system(cmd)
        sys.exit(<span class="dv">0</span>)
    usages <span class="op">=</span> <span class="st">&quot;</span><span class="sc">%prog</span><span class="st"> -i file&quot;</span>
    parser <span class="op">=</span> OP(usage<span class="op">=</span>usages)
    parser.add_option(<span class="st">&quot;-i&quot;</span>, <span class="st">&quot;--input-file&quot;</span>, dest<span class="op">=</span><span class="st">&quot;filein&quot;</span>,
        metavar<span class="op">=</span><span class="st">&quot;FILEIN&quot;</span>, <span class="bu">help</span><span class="op">=</span><span class="st">&quot;The name of input file. \</span>
<span class="st">Standard input is accepted.&quot;</span>)
    parser.add_option(<span class="st">&quot;-v&quot;</span>, <span class="st">&quot;--verbose&quot;</span>, dest<span class="op">=</span><span class="st">&quot;verbose&quot;</span>,
        default<span class="op">=</span><span class="dv">0</span>, <span class="bu">help</span><span class="op">=</span><span class="st">&quot;Show process information&quot;</span>)
    parser.add_option(<span class="st">&quot;-d&quot;</span>, <span class="st">&quot;--debug&quot;</span>, dest<span class="op">=</span><span class="st">&quot;debug&quot;</span>,
        default<span class="op">=</span><span class="va">False</span>, <span class="bu">help</span><span class="op">=</span><span class="st">&quot;Debug the program&quot;</span>)
    (options, args) <span class="op">=</span> parser.parse_args(argv[<span class="dv">1</span>:])
    <span class="cf">assert</span> options.filein <span class="op">!=</span> <span class="va">None</span>, <span class="st">&quot;A filename needed for -i&quot;</span>
    <span class="cf">return</span> (options, args)
<span class="co">##--------------------------------------------------------------------</span>


<span class="kw">def</span> main():
    options, args <span class="op">=</span> cmdparameter(sys.argv)
    <span class="co">#-----------------------------------</span>
    <span class="bu">file</span> <span class="op">=</span> options.filein
    verbose <span class="op">=</span> options.verbose
    debug <span class="op">=</span> options.debug
    <span class="co">#-----------------------------------</span>
    <span class="cf">if</span> <span class="bu">file</span> <span class="op">==</span> <span class="st">&#39;-&#39;</span>:
        fh <span class="op">=</span> sys.stdin
    <span class="cf">else</span>:
        fh <span class="op">=</span> <span class="bu">open</span>(<span class="bu">file</span>)
    <span class="co">#--------------------------------</span>
    <span class="cf">for</span> line <span class="op">in</span> fh:
        <span class="cf">pass</span>
    <span class="co">#-------------END reading file----------</span>
    <span class="co">#----close file handle for files-----</span>
    <span class="cf">if</span> <span class="bu">file</span> <span class="op">!=</span> <span class="st">&#39;-&#39;</span>:
        fh.close()
    <span class="co">#-----------end close fh-----------</span>
    <span class="cf">if</span> verbose:
        <span class="bu">print</span>(<span class="st">&quot;--Successful </span><span class="sc">%s</span><span class="st">&quot;</span> <span class="op">%</span> strftime(timeformat, localtime()), 
              <span class="bu">file</span><span class="op">=</span>sys.stderr)
<span class="cf">if</span> <span class="va">__name__</span> <span class="op">==</span> <span class="st">&#39;__main__&#39;</span>:
    startTime <span class="op">=</span> strftime(timeformat, localtime())
    main()
    endTime <span class="op">=</span> strftime(timeformat, localtime())
    fh <span class="op">=</span> <span class="bu">open</span>(<span class="st">&#39;python.log&#39;</span>, <span class="st">&#39;a&#39;</span>)
    <span class="bu">print</span>(<span class="st">&quot;</span><span class="sc">%s</span><span class="ch">\n\t</span><span class="st">Run time : </span><span class="sc">%s</span><span class="st"> - </span><span class="sc">%s</span><span class="st"> &quot;</span> <span class="op">%</span> <span class="op">\</span>
        (<span class="st">&#39; &#39;</span>.join(sys.argv), startTime, endTime), <span class="bu">file</span><span class="op">=</span>sys.stderr)
    fh.close()</code></pre></div>
<pre><code>Writing skeleton.py</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">%</span>run skeleton <span class="op">-</span>h</code></pre></div>
<pre><code>Usage: skeleton.py -i file

Options:
  -h, --help            show this help message and exit
  -i FILEIN, --input-file=FILEIN
                        The name of input file. Standard input is accepted.
  -v VERBOSE, --verbose=VERBOSE
                        Show process information
  -d DEBUG, --debug=DEBUG
                        Debug the program</code></pre>
<div id="section-2.8.1" class="section level3">
<h3><span class="header-section-number">2.8.1</span> 作业（三）</h3>
<ol start="7" style="list-style-type: decimal">
<li>使 “作业（二）” 中的程序都能接受命令行参数
<ul>
<li>用到的知识点
<ul>
<li>import sys</li>
<li>sys.argv</li>
<li>import optparse</li>
</ul></li>
</ul></li>
<li>备注
<ul>
<li>每个提到提到的“用到的知识点”为相对于前面的题目新增的知识点，请综合考虑。此外，对于不同的思路并不是所有提到的知识点都会用着，而且也可能会用到未提到的知识点。但是所有知识点都在前面的讲义部分有介绍。</li>
<li>每个程序对于你身边会写的人来说都很简单，因此你一定要克制住，独立去把答案做出，多看错误提示，多比对程序输出结果和预期结果的差异。</li>
<li>学习锻炼“读程序”，即对着文件模拟整个的读入、处理过程来发现可能的逻辑问题。</li>
<li>程序运行没有错误不代表你写的程序完成了你的需求，你要去插眼输出结果是不是你想要的。</li>
</ul></li>
<li>关于程序调试
<ul>
<li>在初写程序时，可能会出现各种各样的错误，常见的有缩进不一致，变量名字拼写错误，丢失冒号，文件名未加引号等，这时要根据错误提示查看错误类型是什么，出错的是哪一行来定位错误。当然，有的时候报错的行自身不一定有错，可能是其前面或后面的行出现了错误。</li>
<li>当结果不符合预期时，要学会使用print来查看每步的操作是否正确，比如我读入了字典，我就打印下字典，看看读入的是不是我想要的，是否含有不该存在的字符；或者在每个判断句、函数调入的情况下打印个字符，来跟踪程序的运行轨迹。</li>
</ul></li>
</ol>
</div>
</div>
<div id="python" class="section level2">
<h2><span class="header-section-number">2.9</span> 更多Python内容</h2>
<p><a id="单语句块"></a></p>
<div id="section-2.9.1" class="section level3">
<h3><span class="header-section-number">2.9.1</span> <strong>单语句块</strong></h3>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="cf">if</span> <span class="va">True</span>:
    <span class="bu">print</span>(<span class="st">&#39;yes&#39;</span>)

<span class="cf">if</span> <span class="va">True</span>: <span class="bu">print</span>(<span class="st">&#39;yes&#39;</span>)

x <span class="op">=</span> <span class="dv">5</span>
y <span class="op">=</span> <span class="dv">3</span>

<span class="cf">if</span> x <span class="op">&gt;</span> y:
    <span class="bu">print</span>(y)
<span class="cf">else</span>:
    <span class="bu">print</span>(x)
<span class="co">##-------------</span>
<span class="bu">print</span>((y <span class="cf">if</span> y <span class="op">&lt;</span> x <span class="cf">else</span> x))
<span class="bu">print</span>(x)</code></pre></div>
<pre><code>yes
yes
3
3
5</code></pre>
<p><a id="列表综合"></a></p>
</div>
<div id="section-2.9.2" class="section level3">
<h3><span class="header-section-number">2.9.2</span> 列表解析</h3>
<p>生成新列表的简化的for循环</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]
bList <span class="op">=</span> []
<span class="cf">for</span> i <span class="op">in</span> aList:
    bList.append(i <span class="op">*</span> <span class="dv">2</span>)
<span class="co">##-----------------------------------</span>
<span class="co">##nameL = [line.strip() for line in open(file)]</span>

bList <span class="op">=</span> [i <span class="op">*</span> <span class="dv">2</span> <span class="cf">for</span> i <span class="op">in</span> aList]
<span class="bu">print</span>(bList)</code></pre></div>
<pre><code>[2, 4, 6, 8, 10]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;列表解析可以做判断的&quot;</span>)
aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]
bList <span class="op">=</span> [i <span class="op">*</span> <span class="dv">2</span> <span class="cf">for</span> i <span class="op">in</span> aList <span class="cf">if</span> i <span class="op">%</span> <span class="dv">2</span> <span class="op">!=</span> <span class="dv">0</span>]
<span class="bu">print</span>(bList)</code></pre></div>
<pre><code>列表综合可以做判断的
[2, 6, 10]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;列表解析也可以嵌套的&quot;</span>)
aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]
bList <span class="op">=</span> [<span class="dv">5</span>, <span class="dv">4</span>, <span class="dv">3</span>, <span class="dv">2</span>, <span class="dv">1</span>]
bList <span class="op">=</span> [i <span class="op">*</span> j <span class="cf">for</span> i <span class="op">in</span> aList <span class="cf">for</span> j <span class="op">in</span> bList]

<span class="co">## for i in aList:</span>
<span class="co">##    for j in bList:</span>
<span class="co">##        print i * j</span>
<span class="bu">print</span>(bList)</code></pre></div>
<pre><code>列表综合也可以嵌套的
[5, 4, 3, 2, 1, 10, 8, 6, 4, 2, 15, 12, 9, 6, 3, 20, 16, 12, 8, 4, 25, 20, 15, 10, 5]</code></pre>
</div>
<div id="section-2.9.3" class="section level3">
<h3><span class="header-section-number">2.9.3</span> 字典解析</h3>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">aList <span class="op">=</span> [<span class="st">&#39;a&#39;</span>, <span class="st">&#39;b&#39;</span>, <span class="st">&#39;a&#39;</span>, <span class="st">&#39;c&#39;</span>]
aDict <span class="op">=</span> {i:aList.count(i) <span class="cf">for</span> i <span class="op">in</span> aList}
aDict</code></pre></div>
<pre><code>{&#39;a&#39;: 2, &#39;b&#39;: 1, &#39;c&#39;: 1}</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">bDict <span class="op">=</span> {i:j<span class="op">*</span><span class="dv">2</span> <span class="cf">for</span> i,j <span class="op">in</span> aDict.items()}
bDict</code></pre></div>
<pre><code>{&#39;a&#39;: 4, &#39;b&#39;: 2, &#39;c&#39;: 2}</code></pre>
</div>
<div id="section-2.9.4" class="section level3">
<h3><span class="header-section-number">2.9.4</span> 断言</h3>
<p>设定运行过程中必须满足的条件，当情况超出预期时报错。常用于文件读入或格式判断时，有助于预防异常的读入或操作。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="dv">1</span>
b <span class="op">=</span> <span class="dv">2</span>
<span class="cf">assert</span> a <span class="op">==</span> b, <span class="st">&quot;a is </span><span class="sc">%s</span><span class="st">, b is </span><span class="sc">%s</span><span class="st">&quot;</span> <span class="op">%</span> (a, b)

<span class="cf">if</span> a <span class="op">==</span> b:
    <span class="cf">pass</span>
<span class="cf">else</span>:
    <span class="bu">print</span>(<span class="st">&quot;a is </span><span class="sc">%s</span><span class="st">, b is </span><span class="sc">%s</span><span class="st">&quot;</span> <span class="op">%</span> (a, b))</code></pre></div>
<pre><code>---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

&lt;ipython-input-75-9c43179b4557&gt; in &lt;module&gt;()
      1 a = 1
      2 b = 2
----&gt; 3 assert a == b, &quot;a is %s, b is %s&quot; % (a, b)
      4 
      5 if a == b:


AssertionError: a is 1, b is 2</code></pre>
</div>
<div id="section-2.9.5" class="section level3">
<h3><span class="header-section-number">2.9.5</span> 更多字符串方法</h3>
<p>is.X字符串方法</p>
<p>isalpha()是否只含字母</p>
<p>isalnum()是否只是字母或数字</p>
<p>isdecimal()是否只有数字</p>
<p>isspace()是否只有空格制表符换行</p>
<p>istitle()是否字符串为大写开头，后面均为小写字母</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="st">&#39;b1&#39;</span>
a.isalpha()</code></pre></div>
<pre><code>False</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="st">&#39;b c&#39;</span>
a.isalpha()</code></pre></div>
<pre><code>False</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="st">&#39;bc1&#39;</span>
a.isalnum()</code></pre></div>
<pre><code>True</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="st">&#39;1a&#39;</span>
a.isalnum()</code></pre></div>
<pre><code>True</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">&#39;,&#39;</span>.join([<span class="st">&#39;i&#39;</span>, <span class="st">&#39;love&#39;</span>, <span class="st">&#39;python&#39;</span>])</code></pre></div>
<pre><code>&#39;i,love,python&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">&#39;***&#39;</span>.join([<span class="st">&#39;i&#39;</span>, <span class="st">&#39;love&#39;</span>, <span class="st">&#39;python&#39;</span>])</code></pre></div>
<pre><code>&#39;i***love***python&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">&quot;linux R perl C python&quot;</span>.split()</code></pre></div>
<pre><code>[&#39;linux&#39;, &#39;R&#39;, &#39;perl&#39;, &#39;C&#39;, &#39;python&#39;]</code></pre>
<p>文本对齐rjust() ljust() center()</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">&#39;hello&#39;</span>.rjust(<span class="dv">10</span>)</code></pre></div>
<pre><code>&#39;     hello&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">&#39;hello&#39;</span>.rjust(<span class="dv">20</span>,<span class="st">&#39;*&#39;</span>)</code></pre></div>
<pre><code>&#39;***************hello&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">&#39;hello&#39;</span>.center(<span class="dv">20</span>,<span class="st">&#39;-&#39;</span>)</code></pre></div>
<pre><code>&#39;-------hello--------&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> printPicnic(itemsDict, leftWidth, rightWidth):
    <span class="bu">print</span>(<span class="st">&#39;PICNIC ITEMS&#39;</span>.center(leftWidth <span class="op">+</span> rightWidth, <span class="st">&#39;-&#39;</span>))
    <span class="cf">for</span> k, v <span class="op">in</span> itemsDict.items():
        <span class="bu">print</span>(k.ljust(leftWidth, <span class="st">&#39;.&#39;</span>) <span class="op">+</span> <span class="bu">str</span>(v).rjust(rightWidth))


picnicItems <span class="op">=</span> {<span class="st">&#39;sandwiches&#39;</span>: <span class="dv">4</span>, <span class="st">&#39;apples&#39;</span>: <span class="dv">12</span>, <span class="st">&#39;cups&#39;</span>: <span class="dv">4</span>, <span class="st">&#39;cookies&#39;</span>: <span class="dv">8000</span>}
printPicnic(picnicItems, <span class="dv">12</span>, <span class="dv">5</span>)
printPicnic(picnicItems, <span class="dv">20</span>, <span class="dv">6</span>)</code></pre></div>
<pre><code>---PICNIC ITEMS--
sandwiches..    4
apples......   12
cups........    4
cookies..... 8000
-------PICNIC ITEMS-------
sandwiches..........     4
apples..............    12
cups................     4
cookies.............  8000</code></pre>
<p>strip(),rstrip(),lstrip() 删除空白字符</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">spam <span class="op">=</span> <span class="st">&#39;    hello    &#39;</span>
spam</code></pre></div>
<pre><code>&#39;    hello    &#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">spam.strip()</code></pre></div>
<pre><code>&#39;hello&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">spam.rstrip()</code></pre></div>
<pre><code>&#39;    hello&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">spam.lstrip()</code></pre></div>
<pre><code>&#39;hello    &#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="st">&#39;Hello world, welcome to python world&#39;</span>
a.strip(<span class="st">&#39;d&#39;</span>)</code></pre></div>
<pre><code>&#39;Hello world, welcome to python worl&#39;</code></pre>
<p><a id="lmfr"></a></p>
</div>
<div id="lambda-map-filer-reduce-" class="section level3">
<h3><span class="header-section-number">2.9.6</span> lambda, map, filer, reduce (保留节目)</h3>
<ul>
<li>lambda产生一个没有名字的函数，通常为了满足一次使用，其使用语法为<code>lambda argument_list: expression</code>。参数列表是用逗号分隔开的一个列表，表达式是这些参数的组合操作。</li>
<li>map执行一个循环操作，使用语法为<code>map(func, seq)</code>。第一个参数是要调用的函数或函数的名字，第二个参数是一个序列（如列表、字符串、字典）。map会以序列的每个元素为参数调用func，并新建一个输出列表。</li>
<li>filter用于过滤列表，使用语法为<code>filter(func, list)</code>。以第二个参数的每个元素调用func，返回值为True则保留，否则舍弃。</li>
<li>reduce连续对列表的元素应用函数，使用语法为<code>reduce(func, list)</code>。如果我们有一个列表aList = [1,2,3, … ,n ], 调用<code>reduce(func, aList)</code>后进行的操作为: 首先前两个元素会传入函数func做运算，返回值替换这两个元素，成为数组第一个元素aList = [func(1,2),3, … , n];然后当前的前两个元素再传图func函数做运算，返回值返回值替换这两个元素，成为数组第一个元素aList = [func(func(1,2),3), … , n]，直到列表只有一个元素。</li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;求和函数&quot;</span>)


<span class="kw">def</span> f(x, y): <span class="cf">return</span> x <span class="op">+</span> y


<span class="bu">print</span>(f([<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>], [<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>]))
<span class="bu">print</span>(f(<span class="dv">10</span>, <span class="dv">15</span>))</code></pre></div>
<pre><code>求和函数
[1, 2, 3, 4, 5, 6]
25</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;单个参数的map, lambda调用&quot;</span>)
aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]
<span class="bu">print</span>([x<span class="op">**</span><span class="dv">2</span> <span class="cf">for</span> x <span class="op">in</span> aList])

<span class="bu">print</span>(<span class="st">&quot;多个参数的map, lambda调用&quot;</span>)


<span class="kw">def</span> f(x, y): <span class="cf">return</span> x <span class="op">+</span> y


<span class="bu">print</span>(<span class="bu">list</span>(<span class="bu">map</span>(f, [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>], [<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>])))

<span class="bu">print</span>(<span class="st">&quot;参数为字符串&quot;</span>)
<span class="bu">print</span>([x.upper() <span class="cf">for</span> x <span class="op">in</span> <span class="st">&#39;acdf&#39;</span>])</code></pre></div>
<pre><code>单个参数的map, lambda调用
[1, 4, 9, 16, 25]
多个参数的map, lambda调用
[5, 7, 9]
参数为字符串
[&#39;A&#39;, &#39;C&#39;, &#39;D&#39;, &#39;F&#39;]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">&quot;输出所有的奇数&quot;</span>)
aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]
<span class="bu">print</span>([x <span class="cf">for</span> x <span class="op">in</span> aList <span class="cf">if</span> x <span class="op">%</span> <span class="dv">2</span>])</code></pre></div>
<pre><code>输出所有的奇数
[1, 3, 5]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">from</span> functools <span class="im">import</span> <span class="bu">reduce</span>
<span class="bu">print</span>(<span class="st">&quot;列表求和&quot;</span>)
aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]
<span class="bu">print</span>(<span class="bu">reduce</span>(<span class="kw">lambda</span> a, b: a <span class="op">+</span> b, aList))</code></pre></div>
<pre><code>列表求和
15</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">from</span> functools <span class="im">import</span> <span class="bu">reduce</span>
<span class="bu">print</span>(<span class="st">&quot;列表取最大值&quot;</span>)
aList <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]
<span class="bu">print</span>(<span class="bu">reduce</span>(<span class="kw">lambda</span> a, b: a <span class="cf">if</span> a <span class="op">&gt;</span> b <span class="cf">else</span> b, aList))</code></pre></div>
<pre><code>列表取最大值
5</code></pre>
<p><a id='ee'></a></p>
</div>
<div id="exec-eval-python-" class="section level3">
<h3><span class="header-section-number">2.9.7</span> <strong>exec, eval (执行字符串python语句, 保留节目)</strong></h3>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="st">&#39;print(&quot;Executing a string as a command&quot;)&#39;</span>
<span class="bu">exec</span>(a)</code></pre></div>
<pre><code>Executing a string as a command</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">a <span class="op">=</span> <span class="st">&#39;(2 + 3) * 5&#39;</span>
<span class="bu">eval</span>(a)</code></pre></div>
<pre><code>25</code></pre>
<p><a id='re'></a></p>
</div>
<div id="section-2.9.8" class="section level3">
<h3><span class="header-section-number">2.9.8</span> 正则表达式</h3>
<p>正则表达式通俗来讲就是模式匹配，给定一个模式，寻找可以配对的子串。在Python中，是使用<code>re</code>模块来实现的。</p>
<p><code>re.compile</code>: 转换正则表达式为模式对象</p>
<p><code>re.match</code>: 在待匹配字符串的起始匹配模式对象</p>
<p><code>re.search</code>: 在待匹配字符串内部搜索第一个匹配对象</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 示例，寻找起始密码子</span>
<span class="im">import</span> re
cds <span class="op">=</span> <span class="st">&quot;ATGACGCTCGGACGACTAATG&quot;</span>
start_codon <span class="op">=</span> re.<span class="bu">compile</span>(<span class="st">&#39;ATG&#39;</span>)
start_codon_match <span class="op">=</span> start_codon.match(cds)
start_codon_match.group()</code></pre></div>
<pre><code>&#39;ATG&#39;</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 如果前面有UTR，起始密码子不在第一位，则match找不到</span>
mRNA <span class="op">=</span> <span class="st">&quot;GTCAATGACGCTCGGACGACTAATG&quot;</span>
start_codon_match <span class="op">=</span> start_codon.match(mRNA)
<span class="cf">if</span> start_codon_match:
    <span class="bu">print</span>(start_codon_match.group())
<span class="cf">else</span>:
    <span class="bu">print</span>(<span class="st">&quot;No start codon found at the beginning of the given sequence.&quot;</span>)</code></pre></div>
<pre><code>No start codon at the beginning of the given sequence.</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 如果前面有UTR，起始密码子不在第一位，则需要使用search</span>
mRNA <span class="op">=</span> <span class="st">&quot;GTCAATGACGCTCGGACGACTAATG&quot;</span>
start_codon_match <span class="op">=</span> start_codon.search(mRNA)
<span class="cf">if</span> start_codon_match:
    <span class="bu">print</span>(start_codon_match.group())
<span class="cf">else</span>:
    <span class="bu">print</span>(<span class="st">&quot;No start codon found in the given sequence.&quot;</span>)</code></pre></div>
<pre><code>ATG</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 如果想找出所有的终止子，则使用findall</span>
mRNA <span class="op">=</span> <span class="st">&quot;ATGATGTAAUAATAGUGA&quot;</span>
stop_codon <span class="op">=</span> re.<span class="bu">compile</span>(<span class="st">&#39;[TU]AA|[TU]AG|[TU]GA&#39;</span>)
<span class="co">##stop_codon = re.compile(&#39;UAA|UAG|UGA&#39;)</span>
stop_codon.findall(mRNA)</code></pre></div>
<pre><code>[&#39;TGA&#39;, &#39;TAA&#39;, &#39;UAA&#39;, &#39;TAG&#39;, &#39;UGA&#39;]</code></pre>
<p>上面的模式中使用了正则表达式的2个特殊符号，<code>|</code>和<code>[]</code>。</p>
<p><code>A|B</code>: 表示A或B有一个匹配就可以，如上面的<code>TAA|TAG</code>；如果想限定<code>|</code>两端的字符的范围，需要使用括号界定，如<code>T(AA|T)AG</code>则表示可以匹配<code>TAAAG</code>或<code>TTAG</code>。</p>
<p><code>[TU]</code>: 中括号的任意字符都可以匹配，既该位置可以是<code>T</code>，也可以是<code>U</code>。此外还可以使用<code>[A-Z]</code>表示所有大写字母，<code>[A-Za-z]</code>表示所有英文字母，<code>[0-9]</code>表示所有阿拉伯数字，也可以写<code>[W-Z5-9_]</code>表示一部分字母、数字和下划线。</p>
<p>匹配某一个motif</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 匹配某一个motif，</span>
<span class="co">## 要求motif</span>
<span class="co">##    第1位为A，</span>
<span class="co">##    第2位任意字符，</span>
<span class="co">##    第3位为T，</span>
<span class="co">##    中间间隔3-5个任意碱基，</span>
<span class="co">##    随后一位是G</span>

seqL <span class="op">=</span> [<span class="st">&quot;ACGTACGT&quot;</span>, <span class="st">&quot;ACTCCCG&quot;</span>,<span class="st">&quot;ACTCCGGG&quot;</span>,<span class="st">&quot;AGTTTTTG&quot;</span>]

<span class="co">## . 表示任意字符 (不包括换行)</span>
<span class="co">## {3,5} 表示前面的字符出现次数为3-5次</span>
pattern <span class="op">=</span> re.<span class="bu">compile</span>(<span class="st">&quot;A.T.{3,5}G&quot;</span>)

<span class="bu">print</span>(<span class="st">&quot;Matched&quot;</span>, <span class="st">&quot;</span><span class="ch">\t</span><span class="st">&quot;</span>,<span class="st">&quot;Matched part&quot;</span>)
<span class="cf">for</span> seq <span class="op">in</span> seqL:
    match <span class="op">=</span> pattern.search(seq)
    <span class="cf">if</span> match:
        <span class="bu">print</span>(seq, <span class="st">&quot;</span><span class="ch">\t</span><span class="st">&quot;</span>,match.group())</code></pre></div>
<pre><code>Matched      Matched part
ACTCCCG      ACTCCCG
ACTCCGGG     ACTCCGGG
AGTTTTTG     AGTTTTTG</code></pre>
<p>根据空格切割字符串</p>
<p>假如有这个一个字符串，<code>&quot;A B  C D , E, F&quot;</code>，是由逗号<code>,</code>和数目不等的空格、TAB键或其组合连接起来的，想拆分开获取单独的部分。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">&quot;A B  C D , E, F&quot;</span>.split(<span class="st">&#39; &#39;</span>)</code></pre></div>
<pre><code>[&#39;A&#39;, &#39;B&#39;, &#39;&#39;, &#39;C&#39;, &#39;D&#39;, &#39;,&#39;, &#39;E,&#39;, &#39;F&#39;]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## []都熟悉了，</span>
<span class="co">## \s: 表示所有的空白，包括空格，TAB键，换行等</span>
<span class="co">## +：表示前面的字符出现1次或多次</span>
<span class="im">import</span> re
pattern <span class="op">=</span> re.<span class="bu">compile</span>(<span class="st">&quot;[,\s]+&quot;</span>)

seq <span class="op">=</span> <span class="st">&quot;A B  C D , E, F&quot;</span>

pattern.split(seq)</code></pre></div>
<pre><code>[&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;]</code></pre>
<p>记忆匹配</p>
<p>假如我们有一些<code>fq.gz</code>文件，想获取其文件名，并输出。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## root和leaf是样品名字</span>
<span class="co">## 第一个下划线后面的是生物重复 rep1, rep2</span>
<span class="co">## 第二个下划线后的1和2分别代表双端测序的左端和右端。</span>
fqL <span class="op">=</span> [<span class="st">&quot;root_rep1_1.fq.gz&quot;</span>, <span class="st">&quot;root_rep1_2.fq.gz&quot;</span>, 
       <span class="co">&quot;root_rep2_1.fq.gz&quot;</span>,<span class="st">&quot;root_rep2_2.fq.gz&quot;</span>, 
       <span class="co">&quot;leaf_rep1_1.fq.gz&quot;</span>, <span class="st">&quot;leaf_rep1_2.fq.gz&quot;</span>, 
       <span class="co">&quot;leaf_rep2_1.fq.gz&quot;</span>,<span class="st">&quot;leaf_rep2_2.fq.gz&quot;</span>]

<span class="co">## * 表示前面字符出现任意多次</span>
<span class="co">## () 在这表示记忆匹配，可以使用下标获取</span>
<span class="co">## \ 是转义字符， \.把.转化为一个正常字符，即这儿匹配的是一个真正的.，</span>
<span class="co">## 而不是任意字符</span>
pattern <span class="op">=</span> re.<span class="bu">compile</span>(<span class="st">&quot;([^_]*)_([^_]*)_[12]\.fq\.gz&quot;</span>)

<span class="cf">for</span> fq <span class="op">in</span> fqL:
    match <span class="op">=</span> pattern.search(fq)
    sample <span class="op">=</span> match.group(<span class="dv">1</span>)
    rep    <span class="op">=</span> match.group(<span class="dv">2</span>)
    <span class="bu">print</span>(sample,rep)</code></pre></div>
<pre><code>root rep1
root rep1
root rep2
root rep2
leaf rep1
leaf rep1
leaf rep2
leaf rep2</code></pre>
<p>匹配替换</p>
<p>国人的名字一般姓在前，名在后，老外写法是名在前，姓在后，现在需要做一个转换操作。</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">## 把下面的名字转为姓在后，名在前</span>
nameL <span class="op">=</span> [<span class="st">&quot;Chen Tong&quot;</span>, <span class="st">&quot;Liu Yongxin&quot;</span>, <span class="st">&quot;Wang Ying&quot;</span>]

<span class="co">## \w: 表示单词字符，等同于[A-Za-z0-9_]</span>
pattern <span class="op">=</span> re.<span class="bu">compile</span>(<span class="st">&quot;(\w+) (\w+)&quot;</span>)

<span class="co">## \2, \1 表示记忆匹配的第一个和第二个，具体的计数方式已最左侧括号为准，</span>
<span class="co">## 最左第一个括号是\1, 第二个是\2.</span>
<span class="cf">for</span> name <span class="op">in</span> nameL:
    <span class="bu">print</span>(pattern.sub(<span class="vs">r&quot;\2 \1&quot;</span>, name))</code></pre></div>
<pre><code>Tong Chen
Yongxin Liu
Ying Wang</code></pre>
<p>更多正则表达式的规则见下图，剩下的就是勤学多练了。</p>
<p><img src="pyre.png" width="100%" style="display: block; margin: auto;" /></p>
<p>图片来源于 <a href="https://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html" class="uri">https://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html</a></p>
<p><a id='plot'></a></p>
</div>
</div>
<div id="python" class="section level2">
<h2><span class="header-section-number">2.10</span> Python画图</h2>
<div id="figuresubplot" class="section level4">
<h4><span class="header-section-number">2.10.0.1</span> Figure和Subplot</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">import</span> matplotlib.pyplot <span class="im">as</span> plt
<span class="im">import</span> numpy <span class="im">as</span> np
<span class="im">import</span> pandas <span class="im">as</span> pd
<span class="im">from</span> numpy.random <span class="im">import</span> randn</code></pre></div>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">x <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">3</span>, <span class="dv">5</span>, <span class="dv">7</span>, <span class="dv">9</span>, <span class="dv">10</span>, <span class="dv">23</span>, <span class="dv">45</span>, <span class="dv">45</span>, <span class="dv">56</span>]
y <span class="op">=</span> [<span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">6</span>, <span class="dv">8</span>, <span class="dv">11</span>, <span class="dv">12</span>, <span class="dv">23</span>, <span class="dv">45</span>, <span class="dv">56</span>, <span class="dv">78</span>]


fig <span class="op">=</span> plt.figure()
ax1 <span class="op">=</span> fig.add_subplot(<span class="dv">2</span>, <span class="dv">2</span>, <span class="dv">1</span>)  <span class="co"># 创建4个图的Figure对象，最后的1为选中第一个</span>
ax2 <span class="op">=</span> fig.add_subplot(<span class="dv">2</span>, <span class="dv">2</span>, <span class="dv">2</span>)
ax3 <span class="op">=</span> fig.add_subplot(<span class="dv">2</span>, <span class="dv">2</span>, <span class="dv">3</span>)
ax4 <span class="op">=</span> fig.add_subplot(<span class="dv">2</span>, <span class="dv">2</span>, <span class="dv">4</span>)

ax1.hist(x, y)
ax2.scatter(x, y)
ax4.plot(x, y)

plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_263_0.png" width="100%" style="display: block; margin: auto;" /></p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">fig, axes <span class="op">=</span> plt.subplots(<span class="dv">2</span>, <span class="dv">3</span>)
axes</code></pre></div>
<pre><code>array([[&lt;matplotlib.axes._subplots.AxesSubplot object at 0x000000000B5D88D0&gt;,
        &lt;matplotlib.axes._subplots.AxesSubplot object at 0x0000000009A87FD0&gt;,
        &lt;matplotlib.axes._subplots.AxesSubplot object at 0x000000000B3467B8&gt;],
       [&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0000000009CF0390&gt;,
        &lt;matplotlib.axes._subplots.AxesSubplot object at 0x000000000B6CC080&gt;,
        &lt;matplotlib.axes._subplots.AxesSubplot object at 0x000000000B5D9978&gt;]], dtype=object)</code></pre>
<p><code>创建2 X 3图像，可以相当于对二维数组进行索引 参数            说明 nrows           subplot行数 ncols           subplot列数 sharex          所有图使用相同的x轴 sharey          所有图使用相同的y轴 subplot_kw      用于创建各subplot的关键字字典</code>|</p>
</div>
<div id="subplot" class="section level4">
<h4><span class="header-section-number">2.10.0.2</span> 调整subplot周围间距</h4>
<pre><code>subplots_ajust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)
wspace和hspace控制宽度和高度的百分比</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">fig, axes <span class="op">=</span> plt.subplots(<span class="dv">2</span>, <span class="dv">2</span>, sharex<span class="op">=</span><span class="va">True</span>, sharey<span class="op">=</span><span class="va">True</span>)
<span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">2</span>):
    <span class="cf">for</span> j <span class="op">in</span> <span class="bu">range</span>(<span class="dv">2</span>):
        axes[i, j].hist(randn(<span class="dv">500</span>), bins<span class="op">=</span><span class="dv">50</span>, color<span class="op">=</span><span class="st">&#39;k&#39;</span>, alpha<span class="op">=</span><span class="fl">0.5</span>)
plt.subplots_adjust(wspace<span class="op">=</span><span class="dv">0</span>, hspace<span class="op">=</span><span class="dv">0</span>)
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_267_0.png" width="100%" style="display: block; margin: auto;" /></p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">fig, axes <span class="op">=</span> plt.subplots(<span class="dv">2</span>, <span class="dv">2</span>, sharex<span class="op">=</span><span class="va">True</span>, sharey<span class="op">=</span><span class="va">True</span>)
<span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">2</span>):
    <span class="cf">for</span> j <span class="op">in</span> <span class="bu">range</span>(<span class="dv">2</span>):
        axes[i, j].hist(randn(<span class="dv">500</span>), bins<span class="op">=</span><span class="dv">50</span>, color<span class="op">=</span><span class="st">&#39;k&#39;</span>, alpha<span class="op">=</span><span class="fl">0.5</span>)
plt.subplots_adjust(wspace<span class="op">=</span><span class="dv">1</span>, hspace<span class="op">=</span><span class="dv">1</span>)
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_268_0.png" width="100%" style="display: block; margin: auto;" /></p>
</div>
<div id="-" class="section level4">
<h4><span class="header-section-number">2.10.0.3</span> 颜色 标记和线型</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">&quot;&quot;&quot;</span>
<span class="co">绘制绿色虚线</span>
<span class="co">ax.plot(x,y,&#39;g--&#39;)</span>
<span class="co">另一种方式</span>
<span class="co">ax.plot(x,y,linestyle=&#39;--&#39;,color=&#39;g&#39;)</span>
<span class="co">标记点（maker）</span>
<span class="co">&quot;&quot;&quot;</span>
fig, axes <span class="op">=</span> plt.subplots(<span class="dv">1</span>, <span class="dv">2</span>)

axes[<span class="dv">0</span>].plot(randn(<span class="dv">10</span>), <span class="st">&#39;g--&#39;</span>)  <span class="co"># green ---</span>
axes[<span class="dv">1</span>].plot(randn(<span class="dv">10</span>), <span class="st">&#39;ko--&#39;</span>)  <span class="co"># k：black o：圆点</span>

plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_270_0.png" width="100%" style="display: block; margin: auto;" /></p>
</div>
<div id="section-2.10.0.4" class="section level4">
<h4><span class="header-section-number">2.10.0.4</span> 刻度、标签和图例</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">fig <span class="op">=</span> plt.figure()
ax <span class="op">=</span> fig.add_subplot(<span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">1</span>)
ax.plot(randn(<span class="dv">100</span>))
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_272_0.png" width="100%" style="display: block; margin: auto;" /></p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co">&quot;&quot;&quot;修改上图的轴&quot;&quot;&quot;</span>

fig <span class="op">=</span> plt.figure()
ax <span class="op">=</span> fig.add_subplot(<span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">1</span>)
ax.plot(randn(<span class="dv">100</span>))

ticks <span class="op">=</span> ax.set_xticks([<span class="dv">0</span>, <span class="dv">25</span>, <span class="dv">50</span>, <span class="dv">75</span>, <span class="dv">100</span>])  <span class="co"># 设置刻度</span>
labels <span class="op">=</span> ax.set_xticklabels(
    [<span class="st">&#39;first&#39;</span>, <span class="st">&#39;second&#39;</span>, <span class="st">&#39;third&#39;</span>, <span class="st">&#39;forth&#39;</span>, <span class="st">&#39;fifth&#39;</span>], rotation<span class="op">=</span><span class="dv">30</span>, fontsize<span class="op">=</span><span class="st">&#39;small&#39;</span>)  <span class="co"># 设置x轴标签</span>

ax.set_title(<span class="st">&#39;my first matplot plot&#39;</span>)  <span class="co"># 设置图片标题</span>

ax.set_xlabel(<span class="st">&#39;Stages&#39;</span>)  <span class="co"># 设置x轴名称</span>

plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_273_0.png" width="100%" style="display: block; margin: auto;" /></p>
</div>
<div id="legend" class="section level4">
<h4><span class="header-section-number">2.10.0.5</span> 添加图例legend</h4>
<pre><code>https://matplotlib.org/api/legend_api.html?highlight=legend#module-matplotlib.legend
‘best’          0
‘upper right’   1
‘upper left’    2
‘lower left’    3
‘lower right’   4
‘right’         5
‘center left’   6
‘center right’  7
‘lower center’  8
‘upper center’  9
‘center’        10
bbox_to_anchor=（0.5,0.8）
bbox_to_anchor被赋予的二元组中，第一个数值用于控制legend的左右移动，值越大越向右边移动，
第二个数值用于控制legend的上下移动，值越大，越向上移动</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">fig <span class="op">=</span> plt.figure()
ax <span class="op">=</span> fig.add_subplot(<span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">1</span>)

ax.plot(randn(<span class="dv">10</span>), <span class="st">&#39;k&#39;</span>, label<span class="op">=</span><span class="st">&#39;one&#39;</span>)  <span class="co"># 画一条线，k黑色</span>
ax.plot(randn(<span class="dv">10</span>), <span class="st">&#39;g--&#39;</span>, label<span class="op">=</span><span class="st">&#39;two&#39;</span>)  <span class="co"># 画第二条线，g绿色 - -类型</span>
ax.plot(randn(<span class="dv">10</span>), <span class="st">&#39;ro--&#39;</span>, label<span class="op">=</span><span class="st">&#39;three&#39;</span>)  <span class="co"># 画第三条线红色 ，类型 ...</span>

ax.legend(loc<span class="op">=</span><span class="dv">0</span>, bbox_to_anchor<span class="op">=</span>(<span class="fl">0.5</span>, <span class="fl">0.9</span>))


plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_275_0.png" width="100%" style="display: block; margin: auto;" /></p>
</div>
<div id="section-2.10.0.6" class="section level4">
<h4><span class="header-section-number">2.10.0.6</span> 注解</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">x <span class="op">=</span> [<span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">6</span>, <span class="dv">8</span>, <span class="dv">10</span>, <span class="dv">12</span>]
y <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">3</span>, <span class="dv">5</span>, <span class="dv">7</span>, <span class="dv">9</span>, <span class="dv">11</span>]
fig <span class="op">=</span> plt.figure()
ax <span class="op">=</span> fig.add_subplot(<span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">1</span>)
<span class="co">##ax = fig</span>
ax.plot(x, y, <span class="st">&#39;r--&#39;</span>)

ax.text(<span class="dv">2</span>, <span class="dv">4</span>, <span class="st">&#39;hello python&#39;</span>)
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_277_0.png" width="100%" style="display: block; margin: auto;" /></p>
</div>
<div id="section-2.10.0.7" class="section level4">
<h4><span class="header-section-number">2.10.0.7</span> 图片保存</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">x <span class="op">=</span> [<span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">6</span>, <span class="dv">8</span>, <span class="dv">10</span>, <span class="dv">12</span>]
y <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">3</span>, <span class="dv">5</span>, <span class="dv">7</span>, <span class="dv">9</span>, <span class="dv">11</span>]
fig <span class="op">=</span> plt.figure()
ax <span class="op">=</span> fig.add_subplot(<span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">1</span>)
ax.plot(x, y, <span class="st">&#39;r--&#39;</span>)

ax.text(<span class="dv">2</span>, <span class="dv">4</span>, <span class="st">&#39;hello python&#39;</span>)

<span class="co">## bbox_inches减除当前图片周围空白部分</span>
plt.savefig(<span class="st">&#39;figpath.jpg&#39;</span>, dpi<span class="op">=</span><span class="dv">300</span>, bbox_inches<span class="op">=</span><span class="st">&#39;tight&#39;</span>)</code></pre></div>
</div>
<div id="matplotlib-" class="section level4">
<h4><span class="header-section-number">2.10.0.8</span> matplotlib配置 绘图之前可以调整各种参数字体，全局所有图片的大小等。</h4>
<p>实例</p>
<div id="section-2.10.0.8.1" class="section level5">
<h5><span class="header-section-number">2.10.0.8.1</span> 绘制散点图</h5>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">x <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>]
y <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">4</span>, <span class="dv">9</span>, <span class="dv">16</span>, <span class="dv">25</span>, <span class="dv">36</span>]
plt.scatter(x,  <span class="co"># x轴数据为汽车速度</span>
            y,  <span class="co"># y轴数据为汽车的刹车距离</span>
            s<span class="op">=</span><span class="dv">20</span>,  <span class="co"># 设置点的大小</span>
            c<span class="op">=</span><span class="st">&#39;green&#39;</span>,  <span class="co"># 设置点的颜色</span>
            marker<span class="op">=</span><span class="st">&#39;s&#39;</span>,  <span class="co"># 设置点的形状</span>
            alpha<span class="op">=</span><span class="fl">0.9</span>,  <span class="co"># 设置点的透明度</span>
            linewidths<span class="op">=</span><span class="fl">0.8</span>,  <span class="co"># 设置散点边界的粗细</span>
            edgecolors<span class="op">=</span><span class="st">&#39;red&#39;</span>  <span class="co"># 设置散点边界的颜色</span>
            )

plt.title(<span class="st">&#39;simple scatter plot&#39;</span>)
plt.xlabel(<span class="st">&#39;X&#39;</span>)  <span class="co"># x轴名称</span>
plt.ylabel(<span class="st">&#39;Y&#39;</span>)

plt.show()  <span class="co"># 展示绘图</span></code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_283_0.png" width="100%" style="display: block; margin: auto;" /></p>
</div>
<div id="section-2.10.0.8.2" class="section level5">
<h5><span class="header-section-number">2.10.0.8.2</span> 折线图</h5>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">x <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>]
y <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">4</span>, <span class="dv">9</span>, <span class="dv">16</span>, <span class="dv">25</span>, <span class="dv">36</span>]

plt.plot(x,  <span class="co"># x轴数据</span>
         y,  <span class="co"># y轴数据</span>
         linestyle<span class="op">=</span><span class="st">&#39;-&#39;</span>,  <span class="co"># 折线类型</span>
         linewidth<span class="op">=</span><span class="dv">2</span>,  <span class="co"># 折线宽度</span>
         color<span class="op">=</span><span class="st">&#39;blue&#39;</span>,  <span class="co"># 折线颜色</span>
         marker<span class="op">=</span><span class="st">&#39;o&#39;</span>,  <span class="co"># 点的形状</span>
         markersize<span class="op">=</span><span class="dv">8</span>,  <span class="co"># 点的大小</span>
         markeredgecolor<span class="op">=</span><span class="st">&#39;black&#39;</span>,  <span class="co"># 点的边框色</span>
         markerfacecolor<span class="op">=</span><span class="st">&#39;red&#39;</span>)  <span class="co"># 点的填充色</span>

<span class="co">## 添加标题和坐标轴标签</span>
plt.title(<span class="st">&#39;line plot&#39;</span>)
plt.xlabel(<span class="st">&#39;X&#39;</span>)
plt.ylabel(<span class="st">&#39;Y&#39;</span>)

plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_285_0.png" width="100%" style="display: block; margin: auto;" /></p>
</div>
<div id="section-2.10.0.8.3" class="section level5">
<h5><span class="header-section-number">2.10.0.8.3</span> 直方图</h5>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">import</span> numpy <span class="im">as</span> np
<span class="im">import</span> pandas <span class="im">as</span> pd
<span class="im">import</span> matplotlib.pyplot <span class="im">as</span> plt

plt.hist(np.random.randn(<span class="dv">50</span>),  <span class="co"># 绘图数据</span>
         bins<span class="op">=</span><span class="dv">50</span>,  <span class="co"># 指定直方图的条形数为20个</span>
         color<span class="op">=</span><span class="st">&#39;red&#39;</span>,  <span class="co"># 指定填充色</span>
         edgecolor<span class="op">=</span><span class="st">&#39;k&#39;</span>,  <span class="co"># 指定直方图的边界色</span>
         label<span class="op">=</span><span class="st">&#39;histogram&#39;</span>)  <span class="co"># 为直方图呈现标签</span>
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_287_0.png" width="100%" style="display: block; margin: auto;" /></p>
</div>
</div>
<div id="section-2.10.0.9" class="section level4">
<h4><span class="header-section-number">2.10.0.9</span> 直条图</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">x <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>]
y <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">4</span>, <span class="dv">9</span>, <span class="dv">16</span>, <span class="dv">25</span>, <span class="dv">36</span>]

plt.bar(x, y,
        color<span class="op">=</span><span class="st">&#39;steelblue&#39;</span>,
        alpha<span class="op">=</span><span class="fl">0.8</span>)

plt.title(<span class="st">&#39;bar plot&#39;</span>)

plt.ylim([<span class="dv">0</span>, <span class="dv">40</span>])
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_289_0.png" width="100%" style="display: block; margin: auto;" /></p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">x <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>]
y <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">4</span>, <span class="dv">9</span>, <span class="dv">16</span>, <span class="dv">25</span>, <span class="dv">36</span>]

plt.barh(x, y,
         color<span class="op">=</span><span class="st">&#39;steelblue&#39;</span>,
         alpha<span class="op">=</span><span class="fl">0.8</span>)

plt.title(<span class="st">&#39;bar plot&#39;</span>)

plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_290_0.png" width="100%" style="display: block; margin: auto;" /></p>
</div>
<div id="section-2.10.0.10" class="section level4">
<h4><span class="header-section-number">2.10.0.10</span> 箱线图</h4>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">x <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>]
plt.boxplot(x,
            patch_artist<span class="op">=</span><span class="va">True</span>,  <span class="co"># 箱体添加颜色</span>
            labels<span class="op">=</span>[<span class="st">&#39;boxplot&#39;</span>],  <span class="co"># 添加具体的标签名称</span>
            showmeans<span class="op">=</span><span class="va">True</span>, )

<span class="co">## 显示图形</span>
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_292_0.png" width="100%" style="display: block; margin: auto;" /></p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">np.random.seed(<span class="dv">2</span>)  <span class="co"># 设置随机种子</span>
df <span class="op">=</span> pd.DataFrame(np.random.rand(<span class="dv">5</span>, <span class="dv">4</span>),
                  columns<span class="op">=</span>([<span class="st">&#39;A&#39;</span>, <span class="st">&#39;B&#39;</span>, <span class="st">&#39;C&#39;</span>, <span class="st">&#39;D&#39;</span>]))
df</code></pre></div>

<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>0.435995</td>
      <td>0.025926</td>
      <td>0.549662</td>
      <td>0.435322</td>
    </tr>
    <tr>
      <th>1</th>
      <td>0.420368</td>
      <td>0.330335</td>
      <td>0.204649</td>
      <td>0.619271</td>
    </tr>
    <tr>
      <th>2</th>
      <td>0.299655</td>
      <td>0.266827</td>
      <td>0.621134</td>
      <td>0.529142</td>
    </tr>
    <tr>
      <th>3</th>
      <td>0.134580</td>
      <td>0.513578</td>
      <td>0.184440</td>
      <td>0.785335</td>
    </tr>
    <tr>
      <th>4</th>
      <td>0.853975</td>
      <td>0.494237</td>
      <td>0.846561</td>
      <td>0.079645</td>
    </tr>
  </tbody>
</table>
</div>

<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">data <span class="op">=</span> []
<span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">4</span>):
    data.append(df.iloc[:, i])
data</code></pre></div>
<pre><code>[0    0.435995
 1    0.420368
 2    0.299655
 3    0.134580
 4    0.853975
 Name: A, dtype: float64, 0    0.025926
 1    0.330335
 2    0.266827
 3    0.513578
 4    0.494237
 Name: B, dtype: float64, 0    0.549662
 1    0.204649
 2    0.621134
 3    0.184440
 4    0.846561
 Name: C, dtype: float64, 0    0.435322
 1    0.619271
 2    0.529142
 3    0.785335
 4    0.079645
 Name: D, dtype: float64]</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">plt.boxplot(data)
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_295_0.png" width="100%" style="display: block; margin: auto;" /></p>
<pre><code>plt.boxplot(x, notch=None, sym=None, vert=None, 
             whis=None, positions=None, widths=None, 
             patch_artist=None, meanline=None, showmeans=None, 
             showcaps=None, showbox=None, showfliers=None, 
             boxprops=None, labels=None, flierprops=None, 
             medianprops=None, meanprops=None, 
             capprops=None, whiskerprops=None)

x：指定要绘制箱线图的数据；
notch：是否是凹口的形式展现箱线图，默认非凹口；
sym：指定异常点的形状，默认为+号显示；
vert：是否需要将箱线图垂直摆放，默认垂直摆放；
whis：指定上下须与上下四分位的距离，默认为1.5倍的四分位差；
positions：指定箱线图的位置，默认为[0,1,2…]；
widths：指定箱线图的宽度，默认为0.5；
patch_artist：是否填充箱体的颜色；
meanline：是否用线的形式表示均值，默认用点来表示；
showmeans：是否显示均值，默认不显示；
showcaps：是否显示箱线图顶端和末端的两条线，默认显示；
showbox：是否显示箱线图的箱体，默认显示；
showfliers：是否显示异常值，默认显示；
boxprops：设置箱体的属性，如边框色，填充色等；
labels：为箱线图添加标签，类似于图例的作用；
filerprops：设置异常值的属性，如异常点的形状、大小、填充色等；
medianprops：设置中位数的属性，如线的类型、粗细等；
meanprops：设置均值的属性，如点的大小、颜色等；
capprops：设置箱线图顶端和末端线条的属性，如颜色、粗细等；
whiskerprops：设置须的属性，如颜色、粗细、线的类型等；</code></pre>
<div id="section-2.10.0.10.1" class="section level5">
<h5><span class="header-section-number">2.10.0.10.1</span> 饼图</h5>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">data <span class="op">=</span> [<span class="fl">0.2</span>, <span class="fl">0.3</span>, <span class="fl">0.4</span>, <span class="fl">0.1</span>]
plt.pie(data)
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_298_0.png" width="100%" style="display: block; margin: auto;" /></p>
<pre><code>plt.pie(x, explode=None, labels=None, colors=None, 
        autopct=None, pctdistance=0.6, shadow=False, 
        labeldistance=1.1, startangle=None, 
        radius=None, counterclock=True, wedgeprops=None, 
        textprops=None, center=(0, 0), frame=False)
        
x：指定绘图的数据；
explode：指定饼图某些部分的突出显示，即呈现爆炸式；
labels：为饼图添加标签说明，类似于图例说明；
colors：指定饼图的填充色；
autopct：自动添加百分比显示，可以采用格式化的方法显示；
pctdistance：设置百分比标签与圆心的距离；
shadow：是否添加饼图的阴影效果；
labeldistance：设置各扇形标签（图例）与圆心的距离；
startangle：设置饼图的初始摆放角度；
radius：设置饼图的半径大小；
counterclock：是否让饼图按逆时针顺序呈现；
wedgeprops：设置饼图内外边界的属性，如边界线的粗细、颜色等；
textprops：设置饼图中文本的属性，如字体大小、颜色等；
center：指定饼图的中心点位置，默认为原点
frame：是否要显示饼图背后的图框，如果设置为True的话，需要同时控制图框x轴、y轴的范围和饼图的中心位置；</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"></code></pre></div>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">%</span>matplotlib inline
<span class="im">from</span> mpl_toolkits.mplot3d <span class="im">import</span> axes3d
<span class="im">import</span> matplotlib.pyplot <span class="im">as</span> plt
<span class="im">from</span> matplotlib <span class="im">import</span> cm

fig <span class="op">=</span> plt.figure()
ax <span class="op">=</span> fig.add_subplot(<span class="dv">111</span>, projection<span class="op">=</span><span class="st">&#39;3d&#39;</span>)
X, Y, Z <span class="op">=</span> axes3d.get_test_data(<span class="fl">0.05</span>)
cset <span class="op">=</span> ax.contour(X, Y, Z, cmap<span class="op">=</span>cm.coolwarm)
ax.clabel(cset, fontsize<span class="op">=</span><span class="dv">9</span>, inline<span class="op">=</span><span class="dv">1</span>)

plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_301_0.png" width="100%" style="display: block; margin: auto;" /></p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">import</span> matplotlib <span class="im">as</span> mpl
<span class="im">from</span> mpl_toolkits.mplot3d <span class="im">import</span> Axes3D
<span class="im">import</span> numpy <span class="im">as</span> np
<span class="im">import</span> matplotlib.pyplot <span class="im">as</span> plt

mpl.rcParams[<span class="st">&#39;legend.fontsize&#39;</span>] <span class="op">=</span> <span class="dv">10</span>

fig <span class="op">=</span> plt.figure()
ax <span class="op">=</span> fig.gca(projection<span class="op">=</span><span class="st">&#39;3d&#39;</span>)
<span class="co">##theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)</span>
<span class="co">##z = np.linspace(-2, 2, 100)</span>
<span class="co">##r = z**2 + 1</span>
<span class="co">##x = r * np.sin(theta)</span>
<span class="co">##y = r * np.cos(theta)</span>
x <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>]
y <span class="op">=</span> [<span class="fl">1.5</span>, <span class="dv">1</span>, <span class="dv">2</span>]
z <span class="op">=</span> [<span class="dv">2</span>, <span class="dv">1</span>, <span class="dv">3</span>]
ax.plot(x, y, z, label<span class="op">=</span><span class="st">&#39;parametric curve&#39;</span>)
ax.legend()

plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_302_0.png" width="100%" style="display: block; margin: auto;" /></p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">from</span> matplotlib <span class="im">import</span> pyplot <span class="im">as</span> plt
<span class="im">from</span> matplotlib.patches <span class="im">import</span> Rectangle
someX, someY <span class="op">=</span> <span class="fl">0.5</span>, <span class="fl">0.5</span>
fig, ax <span class="op">=</span> plt.subplots()
currentAxis <span class="op">=</span> plt.gca()
currentAxis.add_patch(Rectangle((someX <span class="op">-</span> <span class="fl">0.1</span>, someY <span class="op">-</span> <span class="fl">0.1</span>), <span class="fl">0.2</span>, <span class="fl">0.2</span>,
                                alpha<span class="op">=</span><span class="dv">1</span>, facecolor<span class="op">=</span><span class="st">&#39;none&#39;</span>))
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_303_0.png" width="100%" style="display: block; margin: auto;" /></p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">from</span> mpl_toolkits.mplot3d <span class="im">import</span> Axes3D
<span class="im">from</span> mpl_toolkits.mplot3d.art3d <span class="im">import</span> Poly3DCollection
<span class="im">import</span> matplotlib.pyplot <span class="im">as</span> plt
fig <span class="op">=</span> plt.figure()
ax <span class="op">=</span> Axes3D(fig)

x <span class="op">=</span> [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">2</span>]
y <span class="op">=</span> [<span class="dv">1</span>,<span class="dv">0</span>,<span class="dv">2</span>]
z <span class="op">=</span> [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">0</span>]
verts <span class="op">=</span> [<span class="bu">zip</span>(x, y,z)]
ax.add_collection3d(Poly3DCollection(verts,edgecolors<span class="op">=</span><span class="st">&#39;red&#39;</span>, facecolors<span class="op">=</span><span class="st">&#39;red&#39;</span>))
x <span class="op">=</span> [<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">1</span>]
y <span class="op">=</span> [<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">1</span>]
z <span class="op">=</span> [<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">0</span>]
verts <span class="op">=</span> [<span class="bu">zip</span>(x, y,z)]
verts <span class="op">=</span> [[(<span class="dv">1</span>,<span class="dv">1</span>,<span class="dv">1</span>), (<span class="dv">2</span>,<span class="dv">0</span>,<span class="dv">2</span>),(<span class="dv">2</span>,<span class="dv">2</span>,<span class="dv">0</span>)],[(<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">0</span>),(<span class="dv">1</span>,<span class="dv">0</span>,<span class="dv">1</span>),(<span class="dv">1</span>,<span class="dv">1</span>,<span class="dv">0</span>)]]
ax.add_collection3d(Poly3DCollection(verts))
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_304_0.png" width="100%" style="display: block; margin: auto;" /></p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">from</span> mpl_toolkits.mplot3d <span class="im">import</span> Axes3D
<span class="im">from</span> mpl_toolkits.mplot3d.art3d <span class="im">import</span> Poly3DCollection
<span class="im">import</span> matplotlib.pyplot <span class="im">as</span> plt
fig <span class="op">=</span> plt.figure()
ax <span class="op">=</span> Axes3D(fig)

verts <span class="op">=</span> [[(<span class="fl">0.5</span>,<span class="fl">0.5</span>,<span class="fl">0.5</span>), (<span class="fl">1.2</span>,<span class="dv">0</span>,<span class="fl">1.2</span>),(<span class="fl">1.2</span>,<span class="fl">1.2</span>,<span class="dv">0</span>)],[(<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">0</span>),(<span class="dv">1</span>,<span class="dv">0</span>,<span class="dv">1</span>),(<span class="dv">1</span>,<span class="dv">1</span>,<span class="dv">0</span>)]]
ax.add_collection3d(Poly3DCollection(verts, edgecolors<span class="op">=</span>[<span class="st">&#39;blue&#39;</span>,<span class="st">&#39;red&#39;</span>], facecolors<span class="op">=</span>[<span class="st">&#39;blue&#39;</span>,<span class="st">&#39;red&#39;</span>]))
plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_305_0.png" width="100%" style="display: block; margin: auto;" /></p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">from</span> matplotlib <span class="im">import</span> pyplot <span class="im">as</span> plt
<span class="im">from</span> mpl_toolkits.mplot3d.art3d <span class="im">import</span> Poly3DCollection

fig <span class="op">=</span> plt.figure()
ax <span class="op">=</span> fig.add_subplot(<span class="dv">111</span>, projection<span class="op">=</span><span class="st">&#39;3d&#39;</span>)

x <span class="op">=</span> [<span class="fl">0.5</span>, <span class="fl">1.2</span>, <span class="fl">1.2</span>, <span class="dv">0</span>, <span class="dv">1</span>, <span class="dv">1</span>]
y <span class="op">=</span> [<span class="fl">0.5</span>, <span class="dv">0</span>,   <span class="fl">1.2</span>, <span class="dv">0</span>, <span class="dv">0</span>, <span class="dv">1</span>]
z <span class="op">=</span> [<span class="fl">0.5</span>, <span class="fl">1.2</span>, <span class="dv">0</span>,   <span class="dv">0</span>, <span class="dv">1</span>, <span class="dv">0</span>]

poly3d <span class="op">=</span> [[(<span class="fl">0.5</span>,<span class="fl">0.5</span>,<span class="fl">0.5</span>), (<span class="fl">1.2</span>,<span class="dv">0</span>,<span class="fl">1.2</span>),(<span class="fl">1.2</span>,<span class="fl">1.2</span>,<span class="dv">0</span>)],[(<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">0</span>),(<span class="dv">1</span>,<span class="dv">0</span>,<span class="dv">1</span>),(<span class="dv">1</span>,<span class="dv">1</span>,<span class="dv">0</span>)]]
ax.scatter(x,y,z)
ax.add_collection3d(Poly3DCollection(poly3d, edgecolors<span class="op">=</span>[<span class="st">&#39;red&#39;</span>,<span class="st">&#39;blue&#39;</span>], facecolors<span class="op">=</span><span class="st">&#39;w&#39;</span>, linewidths<span class="op">=</span><span class="dv">1</span>, alpha<span class="op">=</span><span class="fl">0.5</span>))

plt.show()</code></pre></div>
<p><img src="02_CT_Python_training-chinese_files/02_CT_Python_training-chinese_306_0.png" width="100%" style="display: block; margin: auto;" /></p>
</div>
</div>
</div>
<div id="reference" class="section level2">
<h2><span class="header-section-number">2.11</span> Reference</h2>
<ul>
<li><a href="http://www.byteofpython.info/" class="uri">http://www.byteofpython.info/</a></li>
<li><a href="http://woodpecker.org.cn/abyteofpython_cn/chinese/index.html" class="uri">http://woodpecker.org.cn/abyteofpython_cn/chinese/index.html</a></li>
<li><a href="http://www.python-course.eu/" class="uri">http://www.python-course.eu/</a></li>
<li><a href="http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-189-a-gentle-introduction-to-programming-using-python-january-iap-2008/" class="uri">http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-189-a-gentle-introduction-to-programming-using-python-january-iap-2008/</a></li>
<li><a href="http://my.oschina.net/taogang/blog/286954" class="uri">http://my.oschina.net/taogang/blog/286954</a></li>
</ul>

</div>
</div>
            </section>

          </div>
        </div>
      </div>
<a href="pythonbasic.html" class="navigation navigation-prev " aria-label="Previous page"><i class="fa fa-angle-left"></i></a>
<a href="Python-plot-WXN.html" class="navigation navigation-next " aria-label="Next page"><i class="fa fa-angle-right"></i></a>
    </div>
  </div>
<script src="libs/gitbook-2.6.7/js/app.min.js"></script>
<script src="libs/gitbook-2.6.7/js/lunr.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-search.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-sharing.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-fontsettings.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-bookdown.js"></script>
<script src="libs/gitbook-2.6.7/js/jquery.highlight.js"></script>
<script>
gitbook.require(["gitbook"], function(gitbook) {
gitbook.start({
"sharing": {
"github": false,
"facebook": false,
"twitter": false,
"google": false,
"weibo": false,
"instapper": false,
"vk": false,
"all": ["facebook", "google", "twitter", "weibo", "instapaper"]
},
"fontsettings": {
"theme": "white",
"family": "sans",
"size": 2
},
"edit": {
"link": null,
"text": null
},
"download": ["Py3_course.pdf"],
"toc": {
"collapse": "subsection"
}
});
});
</script>

</body>

</html>
